Falmarri Falmarri - 1 year ago 191
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()

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

Answer Source

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())): 

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())): 

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download