Search code examples
pythonlayoutpyqtqscrollareaqgridlayout

Updating dynamic QGridLayout - Python PyQt


I recently started studying Python and now I'm making a software with a GUI using PyQt Libraries.

Here's my problem: I create a Scrollarea, I put in this scrollarea a widget which contains a QGridLayout.

    sa = QtGui.QScrollArea()
    sa_widget = QtGui.QWidget()
    self.sa_grid.setSizeConstraint(QtGui.QLayout.SetMinAndMaxSize)
    sa_widget.setLayout(self.sa_grid)
    sa.setWidgetResizable(True)
    sa.setWidget(sa_widget)

Then I add 10 QLabel (this is just an example of course, in this example I'm using a QGridLayout just like a Vertical Layout):

    i = 0
    while i<100:
        i = i +1
        add = QtGui.QLabel("Row %i" % i)
        self.sa_grid.addWidget(add)

Then I create a button that calls the function "function_name", I want that this function deletes a row, so far this is what I've written:

    tmp = QtGui.QWidget()
    tmp = self.sa_grid.itemAt(0)
    self.sa_grid.removeItem(tmp)

It deletes the first row and every x row of the gridlayout becomes row x-1, however, it doesn't delete the text "Row 1" so I see "Row 0" and "Row 1" on the same row.

Anyone can help me?

Thanks a lot in advance, Davide


Solution

  • Removing an item from a layout does not delete it. The item will just become a free-floating object with no associated layout.

    If you want to get rid of the object completely, explicitly delete it:

    def deleteGridWidget(self, index):
        item = self.sa_grid.itemAt(index)
        if item is not None:
            widget = item.widget()
            if widget is not None:
                self.sa_grid.removeWidget(widget)
                widget.deleteLater()