Pyqt无法在删除后添加布局
问题描述:
我想将布局添加到QGroupbox。通过阅读this answer我能够添加我想要的元素没有任何问题。在this answer的帮助下,我学会了如何再次移除小部件。这一切工作正常第一次。当我现在想要将具有相同小部件的布局再次添加到我的QGroupbox时,它们不会出现。Pyqt无法在删除后添加布局
但是,他们似乎在那里,因为我的打印调试显示我,有项目。我知道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)
如何让我的新布局中可见的第一个加法后删除循环?
答
我用一个简单的技巧解决了我的问题。每次我调用变量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