user12314033
user12314033

Reputation: 13

PyQt: Multiple QGridLayout

How can I have multiple QGridLayouts on a single widget? I want to have one grid layout on the left and one on the right.

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys

class FormWidget(QWidget):

    def __init__(self):
        super(FormWidget, self).__init__( )

        self.grid = QGridLayout(self)
        self.grid2 = QGridLayout(self)
        self.grid.addWidget(self.grid2)

    if __name__ == '__main__':

        app = QApplication(sys.argv)
        ex = FormWidget()
        sys.exit(app.exec_())

Upvotes: 1

Views: 1233

Answers (1)

eyllanesc
eyllanesc

Reputation: 244291

If you want to place 2 layouts horizontally then you must use a QHBoxLayout:

import sys
from PyQt5.QtWidgets import QApplication, QGridLayout, QHBoxLayout, QWidget


class FormWidget(QWidget):
    def __init__(self, parent=None):
        super(FormWidget, self).__init__(parent)

        left_grid_layout = QGridLayout()
        right_grid_layout = QGridLayout()

        lay = QHBoxLayout(self)
        lay.addLayout(left_grid_layout)
        lay.addLayout(right_grid_layout)

        self.resize(640, 480)


if __name__ == "__main__":

    app = QApplication(sys.argv)
    ex = FormWidget()
    ex.show()
    sys.exit(app.exec_())

Update:

If you want to set a weight you must set it in the stretch.

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QGridLayout, QHBoxLayout, QTextEdit, QWidget


class FormWidget(QWidget):
    def __init__(self, parent=None):
        super(FormWidget, self).__init__(parent)

        left_grid_layout = QGridLayout()
        right_grid_layout = QGridLayout()

        # for testing
        left_grid_layout.addWidget(QTextEdit())
        right_grid_layout.addWidget(QTextEdit())


        lay = QHBoxLayout(self)
        lay.addLayout(left_grid_layout, stretch=1)
        lay.addLayout(right_grid_layout, stretch=2)

        lay.setContentsMargins(
            0, # left
            100, # top
            0, # right
            100 # bottom
        )

        self.resize(640, 480)


if __name__ == "__main__":

    app = QApplication(sys.argv)
    ex = FormWidget()
    ex.show()
    sys.exit(app.exec_())

Upvotes: 1

Related Questions