Search code examples
pythonqtqt4

Pyqt fails to add layout after removing


I want to add a layout to a QGroupbox. By reading this answer I am able to add my desired elements without any problem. With the help of this answer, I learned how to remove the widgets again. All this works fine the first time. When I now want to add the layout with the same widgets again into my QGroupbox, they don't appear.

However, they seem to be there because my print debugging shows me, that there are items. I am aware of this question which shows how to add widgets dynamically but does not show how to remove them.

My shot:

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)

How to make my new layout visible after the first add and remove loop?


Solution

  • I solved my issue with a simple trick. Error where that I called the variable self.layoutevery time, I pushed the button. By calling the variable in the init-function of my code, I 've got the expected result, that the widgets not only appeared but could be recalled after they were deleted the first time.

    The change is:

    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