4

I've added a QSpacerItem to a layout using its addStretch() method.

layout->addStretch(1);

now i'd like to delete it but i didn't have any reference to it.

how can I browse all QLayoutItem and only delete QSpacerItem ?

László Papp
  • 51,870
  • 39
  • 111
  • 135
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99

2 Answers2

8

I would personally write this:

for (int i = 0; i < layout->count(); ++i) {
    QLayoutItem *layoutItem = layout->itemAt(i);
    if (layoutItem->spacerItem()) {
        layout->removeItem(layoutItem);
        // You could also use: layout->takeAt(i);
        delete layoutItem;
        --i;
    }
}

So, the logic would be this in a nutshell if the code does not make it clear:

  • Look up all the items of the layout.

  • Check if it is a spacer item.

  • If it is, remove it.

László Papp
  • 51,870
  • 39
  • 111
  • 135
  • Iterating backward would be strange to me. The same issue is solved by a simple --i, thanks. Delete is also added, thanks. @Ghilas BELHADJ, you may wish to integrate my bugfixes into your code. – László Papp May 05 '14 at 10:17
0

You should not to delete QLayoutItem if you add it to QLayout. It's QLayout responsibility to delete it children.

Note: The ownership of item is transferred to the layout, and it's the layout's responsibility to delete it.

BOPOHOB
  • 525
  • 1
  • 4
  • 13