Search code examples
pythonpyqtpyqt5qpushbuttonqlayout

adding widgets to nested layouts at runtime


I've been trying to make a small pyqt script where pushbuttons are added when a button is pressed. It works as intended, but only when adding buttons to the main layout. When I try to add the buttons to a nested layout, they don't show up.

Example of the working code:

class Example(QWidget):

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

        self.widget_layout = QVBoxLayout()

        self.btn = QPushButton('add button')
        self.btn.pressed.connect(self.add_button)

        self.widget_layout.addWidget(self.btn)
        self.setLayout(self.widget_layout)

        self.setGeometry(300, 300, 300, 300)
        self.show()

    def add_button(self):
        count = self.widget_layout.count()
        btn = QPushButton(str(count))
        self.widget_layout.addWidget(btn)

Example of the code that's not working:

class Example(QWidget):

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

        self.widget_layout = QVBoxLayout()
        self.button_layout = QVBoxLayout()

        self.btn = QPushButton('add button')
        self.btn.pressed.connect(self.add_button)

        self.widget_layout.addWidget(self.btn)
        self.widget_layout.addItem(self.button_layout)
        self.setLayout(self.widget_layout)

        self.setGeometry(300, 300, 300, 300)
        self.show()

    def add_button(self):
        count = self.button_layout.count()
        btn = QPushButton(str(count+1))
        self.button_layout.addWidget(btn)

Does anyone know why this doesn't work in a nested layout?


Solution

  • If you want to add a layout to another layout then you must use the addLayout() method, instead your code is failing because you use addItem() that expects a QLayoutItem.

    The solution is to change addItem() with addLayout():

    self.widget_layout.addWidget(self.btn)
    self.widget_layout.addLayout(self.button_layout)
    self.setLayout(self.widget_layout)