Skip to content Skip to sidebar Skip to footer

Pyqt5 AddStretch In Between Widgets?

I am using a QVBox layout and there are two widgets and a dynamic layout 'layout2' in the layout. Widget1 is fixed on top Widget3 is fixed at the bottom and widget2 is dynamic widg

Solution 1:

If you only want to change the widget that is in the second position it is not necessary to delete create a new layout, it is only necessary to reuse it, in the following example we see how the widget is changing:

class Screen(QWidget):
    def __init__(self):
        super(Screen, self).__init__()
        self.setLayout(QVBoxLayout())

        widget1 = QPushButton("Text1", self)
        widget3 = QLabel("Text3", self)

        self.widget2_layout = QHBoxLayout()
        self.change_widget2()

        self.layout().addWidget(widget1)
        self.layout().addLayout(self.widget2_layout)
        self.layout().addWidget(widget3)

        widget1.clicked.connect(self.change_widget2)

    def clearLayout(self, layout):
        item = layout.takeAt(0)
        while item:
            w = item.widget()
            if w:
                w.deleteLater()
            lay = item.layout()
            if lay:
                self.clearLayout(item.layout())
            item = layout.takeAt(0)

    def change_widget2(self):
        self.clearLayout(self.widget2_layout)

        # change the widget.
        import random
        widgets = [QLabel, QLineEdit, QPushButton]
        widget2 = widgets[random.randint(0, len(widgets)-1)]("widget2", self)

        self.widget2_layout.addWidget(widget2)

Post a Comment for "Pyqt5 AddStretch In Between Widgets?"