I have a QWidget
in a dialog. Over the course of the program running, several QCheckBox *
objects are added to the layout like this:
The wonderful thing about layouts is that they handle a deletion of a widget automatically. So all you really need is to iterate over the widgets and you're done. Since you want to wipe out all children of a given widget, simply do:
for (auto widget: ui->myWidget::findChildren
({}, Qt::FindDirectChildrenOnly))
delete widget;
No need to worry about layouts at all. This works whether the children were managed by a layout or not.
If you want to be really correct, you would need to ignore the widgets that are child widgets but are stand-alone windows. This would be the case if this was in general-purpose library code:
for (auto widget: ui->myWidget::findChildren
({}, Qt::FindDirectChildrenOnly))
if (! widget->windowFlags() & Qt::Window) delete widget;
Alternatively, if you only want to delete the children managed by a given layout and its sublayouts:
void clearWidgets(QLayout * layout) {
if (! layout)
return;
while (auto item = layout->takeAt(0)) {
delete item->widget();
clearWidgets(item->layout());
}
}