我正在使用QVBox布局,布局中有两个小部件和一个动态布局'layout2'。小部件 1 固定在顶部 小部件 3 固定在底部,小部件 2 是动态小部件。每次都会删除并添加布局 2。这里的问题是我无法将小部件 3 定位在底部,因为布局 2 布局被删除 小部件 3 移动到顶部。下面是示例代码。
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_())
我尝试了添加拉伸,虚拟的附加布局,但没有任何效果。
如果您只想更改位于第二个位置的小部件,则无需删除创建新布局,只需重用它,在以下示例中,我们可以看到小部件是如何变化的:
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)