Qt World Summit: Submit your Presentation

[solved] How to properly delete a QLayoutItem from the layout

  • Hi there!
    I'm trying to delete a Widget out of a layout. The widget can be at an arbitrary (but existing) position and lower items have to move up to close the gap. layout_m is of type QLayout,. Here's my delete member function:
    if(index >= layout_m->count() || index < 0) return;
    QLayoutItem* toDelete = layout_m->takeAt(index);
    if(toDelete != 0){
    delete toDelete;
    This code is inspired from the QLayout documentation's description how to properly delete all contents of a layout. However, as you see, I use toDelete->widget()->setParent(NULL); to break ownership to the QLayoutItem. If I don't do that, the deleted item is still displayed in the parent widget, but not in the layout.
    I conclude that my way to remove an item from a layout is unproper. How should I do that in a clean way?

  • @kalsan As far as I know, QLayout::takeAt() doesn't remove the widget of the QLayoutItem from its parent widget.

    So I think your code is ok. Anyway, take a look at QLayout::removeWidget. I don't know all your code, but maybe you should remove the widget from the layout using that method.

  • I just call:

    delete widgetToRemoveFromLayout;

    everything else does the layout on its own.

  • @msue Right then :)

  • Yay, that's what I was looking for. Thanks!