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.
Detailed Description. QStackedWidget can be used to create a user interface similar to the one provided by QTabWidget . It is a convenience layout widget built on top of the QStackedLayout class. Like QStackedLayout , QStackedWidget can be constructed and populated with a number of child widgets (“pages”):
A QLabel object acts as a placeholder to display non-editable text or image, or a movie of animated GIF. It can also be used as a mnemonic key for other widgets. Plain text, hyperlink or rich text can be displayed on the label.
The provision of drag and drop is very intuitive for the user. It is found in many desktop applications where the user can copy or move objects from one window to another. MIME based drag and drop data transfer is based on QDrag class.
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.
This may be a bit too late but just wanted to add this for future reference:
def clearLayout(layout): while layout.count(): child = layout.takeAt(0) if child.widget(): child.widget().deleteLater()
Adapted from Qt docs http://doc.qt.io/qt-5/qlayout.html#takeAt. Remember that when you are removing children from the layout in a while or for loop, you are effectively modifying the index # of each child item in the layout. That's why you'll run into problems using a for i in range()
loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With