How to delete a widget at once in a QLayout?
-
I tried this way:
print(self.main_ui.findChildren(QLabel)) print(self.main_ui.verticalLayout_6.count()) item = self.main_ui.verticalLayout_6.takeAt(0) item.widget().close() self.main_ui.verticalLayout_6.removeWidget(item.widget()) print(self.main_ui.verticalLayout_6.count()) print(self.main_ui.findChildren(QLabel))
Though it is deleted from the Layout, it still can be found inself.main_ui
. I also tried widget.deleteLater() function, it can delete successfully in self.main_ui, but it can not delete at once. -
Hi,
What do you mean by "it cannot delete at once" ?
deleteLater will trigger the deletion as soon as possible which is usually enough.
What is your current issue ?
What is your goal ? -
Hi, @SGaist
My initial UI has a QGroupBox namesgroup_box_ok
, and you can see from line 739~740 that I want to delete it first. Then I want to add other QGroupBoxes according toclass_names
. For example, class_names is ('ok', 'dog', 'cat'), then I hope there's onlygroup_box_ok
,group_box_dog
andgroup_box_cat
incls_aug_ui
. But the result is:
So the oldgroup_box_ok
was not deleted at once. The following code raises bugs because there's a duplicatedgroup_box_ok
. And I must doing these things in the same function (slot). I want thatcls_aug_ui.findChildren(QGroupBox)
can not find the oldgroup_box_ok
. -
You can remove the parent of the widget you took out of the layout.
-
I found the parent of the widget need to be set as None before removing the widget.
We can remove the widget by this way:widget = self.main_ui.verticalLayout_6.takeAt(0).widget() widget.setParent(None) widget.close() self.main_ui.verticalLayout_6.removeWidget(widget)