我想为QGroupbox添加布局。通过阅读this answer,我可以毫无问题地添加我想要的元素。在this answer的帮助下,我学会了如何再次删除小部件。所有这一切都很好第一次。当我现在想要将具有相同小部件的布局再次添加到我的QGroupbox中时,它们不会出现。
然而,它们似乎在那里因为我的打印调试向我显示,有些项目。我知道this question显示了如何动态添加小部件,但没有显示如何删除它们。
我的镜头:
def test_class(self): #called by a button
self.layout = QGridLayout()
label1 = QLabel('mylabel1')
label2 = QLabel('mylabel2')
combo1 = QComboBox()
self.layout.addWidget(label1,0,0)
self.layout.addWidget(label2,1,0)
self.layout.addWidget(combo1,2,0)
self.grpbox.setLayout(self.layout) # the Qgroupbox which holds the layout
def clearLayout(self, layout):
print "called"
if layout is not None:
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
print item, widget # does print when calling the methods again
if widget is not None:
widget.deleteLater()
else:
self.clearLayout(item.layout())
def test_remove(self): # called by a button
self.clearLayout(self.layout)
如何在第一次添加和删除循环后使我的新布局可见?
答案 0 :(得分:0)
我用一个简单的技巧解决了我的问题。我每次都调用变量self.layout
的错误,我按下了按钮。通过在我的代码的init函数中调用变量,我得到了预期的结果,小部件不仅出现了,而且可以在第一次被删除后被调用。
改变是:
def __init__(self):
self.layout = QGridLayout() # created here rather then in the test_class Function
def test_class(self): #called by a button
label1 = QLabel('mylabel1')
label2 = QLabel('mylabel2')
combo1 = QComboBox()
self.layout.addWidget(label1,0,0)
self.layout.addWidget(label2,1,0)
self.layout.addWidget(combo1,2,0)
self.grpbox.setLayout(self.layout) # the Qgroupbox which holds the layout