Pyqt 删除后无法添加布局

Pyqt fails to add layout after removing

我想向 QGroupbox 添加布局。通过阅读this answer I am able to add my desired elements without any problem. With the help of 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)

如何在第一次添加和删除循环后使我的新布局可见?

我用一个简单的技巧解决了我的问题。我每次都调用变量 self.layout 时出错,我按下了按钮。通过在我的代码的初始化函数中调用变量,我得到了预期的结果,这些小部件不仅出现了,而且在第一次删除后可以被召回。

变化是:

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