Remove everything from a frame in pyqt

2019-04-13 08:42发布

问题:

There are some examples of removing specific items from a layout, but I can not find anything on simply deleting everything from a frame.

Using pyqt designer, I have created a frame. Then using pyuic4 the file is converted to python. In the main program, some layouts, items, and widgets are dynamically inserted to the frame. However, I dont actually keep track of all the items. On a button refresh, I want to delete everything contained in the frame and populate it again.

My question is, is there a simple way to delete everything that is contained in a frame, including layouts, widgets, and items.

As of now, I can do:

for i in range(len(MyResourceFrame.children())):
    MyResourceFrame.children()[i].deleteLater()

However, I have code directly under that, and after the first qframe population, clicking on repopulate give the error that a frame is already there, which then removes all items. The second click on repopulate works. Does this have something to do with "Later" wanting to be out of scope first or is that just a name?

回答1:

The deleteLater slot will just schedule the object for deletion. That is, the object won't be deleted until control returns to the event loop (which will usually mean after the currently executing function has returned).

If you want to delete an object immediately, use the sip module. This should allow you delete a layout and all its contained widgets like this:

import sip
...

class Window(QtGui.QMainWindow):
    ...

    def populateFrame(self):
        self.deleteLayout(self.frame.layout())
        layout = QtGui.QVBoxLayout(self.frame)
        ...

    def deleteLayout(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
                else:
                    self.deleteLayout(item.layout())
            sip.delete(layout)