Pyqt5 addStretch 在小部件之间?

Pyqt5 addStretch in between widgets?

我正在使用 QVBox 布局,布局中有两个小部件和一个动态布局 'layout2'。 Widget1 固定在顶部,Widget3 固定在底部,widget2 是动态小部件。 layout2 每次都被删除和添加。这里的问题是我无法将 widget3 定位在底部,因为 layout2 布局被删除 Widget3 移动到顶部。下面是示例代码。

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

        self.main_layout = QVBoxLayout()
        widget1 = QPushButton("Text1")
        #self.widget2 = QWidget()
        widget3 = QLabel("Text3")
        self.widget2_layout = QHBoxLayout()
        widget2_label = QLabel("text2")
        self.widget2_layout.addWidget(widget2_label)
        #self.widget2.setLayout(self.widget2_layout)
        self.main_layout.addWidget(widget1,Qt.AlignTop)
        self.main_layout.addLayout(self.widget2_layout)
        self.main_layout.addWidget(widget3,Qt.AlignBottom)
        widget1.clicked.connect(self.change_widget2)    
        self.setLayout(self.main_layout)    
        self.show()

    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)
        self.widget2_layout = QHBoxLayout()
        widget2_label = QLabel("text changed")
        self.widget2_layout.addWidget(widget2_label)
        self.main_layout.addLayout(self.widget2_layout)

app = QApplication(sys.argv)
Gui = Screen()
sys.exit(app.exec_())

我尝试了 addstretch、虚拟附加布局,但没有任何效果。

如果您只想更改位于第二个位置的小部件,则无需删除创建新布局,只需重新使用它即可,在以下示例中我们将看到小部件是如何更改的:

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)