The great thing about layouts is that they handle the removal of the widget automatically. So you really need to iterate over the widgets, and you're done. Since you want to destroy all the children of this widget, simply do:
for (auto widget: ui->myWidget::findChildren<QWidget*> ({}, Qt::FindDirectChildrenOnly)) delete widget;
No need to worry about layouts at all. This works regardless of whether the children are controlled according to the layout or not.
If you want to be truly correct, you will need to ignore widgets that are child widgets but are standalone windows. This would be true if it were generally library code:
for (auto widget: ui->myWidget::findChildren<QWidget*> ({}, Qt::FindDirectChildrenOnly)) if (! widget->windowFlags() & Qt::Window) delete widget;
Alternatively, if you want to remove only children controlled by this layout and its sublayers:
void clearWidgets(QLayout * layout) { if (! layout) return; while (auto item = layout->takeAt(0)) { delete item->widget(); clearWidgets(item->layout()); } }
Kuba Ober Mar 25 '14 at 21:42 2014-03-25 21:42
source share