0

I fill my QVBoxLayout dynamically with QWidget objects I create during runtime. I would like to remove them as well during runtime, but how?

I could remove the widgets one by one:

void QLayout::removeWidget(QWidget * widget)

Can I somehow iterate through the layout?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Ralf Wickum
  • 2,850
  • 9
  • 55
  • 103

2 Answers2

6

All roads lead to Rome ;)

The Qt documentation of QLayout::takeAt states:

The following code fragment shows a safe way to remove all items from a layout:

QLayoutItem *child;
while ((child = layout->takeAt(0)) != 0) {
    ...
    delete child;
}

To also delete the managed widget, you need to add just one line:

QLayoutItem *child;
while ((child = layout->takeAt(0)) != 0) {
    ...
    delete child->widget();
    delete child;
}
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Murat
  • 716
  • 1
  • 6
  • 14
2

There's a count method that returns the number of stored widgets, and a itemAt() method that, given an index, it returns the pointer to relative stored widget. You can retrieve all pointers and then remove them. You should first retrieve all pointers, because if you remove one while counting then the number of stored widgets changes during iterations.

itemAt() retrieve a QLayoutItem with a widget method that retrieves the widget itself.

while (layout->count() != 0) {
  QLayoutItem *item = layout->itemAt(0);
  layout->removeWidget(item->widget());
}
Jepessen
  • 11,744
  • 14
  • 82
  • 149