Falmarri Falmarri - 23 days ago 9
Python Question

Clear all widgets in a layout in pyqt

Is there a way to clear (delete) all the widgets in a layout?

self.plot_layout = QtGui.QGridLayout()
self.plot_layout.setGeometry(QtCore.QRect(200,200,200,200))
self.root_layout.addLayout(self.plot_layout)
self.plot_layout.addWidget(MyWidget())


Now I want to replace the widget in
plot_layout
with a new widget. Is there an easy way to clear all the widgets in
plot_layout
? I don't see any method such.

Answer

After a lot of research (and this one took quite time, so I add it here for future reference), this is the way I found to really clear and delete the widgets in a layout:

    for i in reversed(range(layout.count())): 
        layout.itemAt(i).widget().setParent(None)

What the documentation says about the QWidget is that:

The new widget is deleted when its parent is deleted.

Important note: You need to loop backwards because removing things from the beginning shifts items and changes the order of items in the layout.

To test and confirm that the layout is empty:

    for i in range(layout.count()): print i

There seems to be another way to do it. Instead of using the setParent function, use the deleteLater() function like this:

    for i in reversed(range(layout.count())): 
        layout.itemAt(i).widget().deleteLater()

The documentation says that QObject.deleteLater (self)

Schedules this object for deletion.

However, if you run the test code specified above, it prints some values. This indicates that the layout still has items, as opposed to the code with setParent.