How to delete an already existing layout on a widget?

前端 未结 4 395
南笙
南笙 2021-01-04 06:53

You must first delete the existing layout manager (returned by layout()) before you can call setLayout() with the new layout.

相关标签:
4条回答
  • 2021-01-04 07:13

    Chris Wilson's answer is correct, but I've found the layout does not delete sublayouts and qwidgets beneath it. It's best to do it manually if you have complicated layouts or you might have a memory leak.

    QLayout * layout = new QWhateverLayout();
    
    // ... create complicated layout ...
    
    // completely delete layout and sublayouts
    QLayoutItem * item;
    QLayout * sublayout;
    QWidget * widget;
    while ((item = layout->takeAt(0))) {
        if ((sublayout = item->layout()) != 0) {/* do the same for sublayout*/}
        else if ((widget = item->widget()) != 0) {widget->hide(); delete widget;}
        else {delete item;}
    }
    
    // then finally
    delete layout;
    
    0 讨论(0)
  • 2021-01-04 07:14

    I want to remove the current layout, replace it with a new layout but keep all widgets managed by the layout. I found that in this case, Chris Wilson's solution does not work well. The layout is not always changed.

    This worked for me:

    void RemoveLayout (QWidget* widget)
    {
        QLayout* layout = widget->layout ();
        if (layout != 0)
        {
        QLayoutItem *item;
        while ((item = layout->takeAt(0)) != 0)
            layout->removeItem (item);
        delete layout;
        }
    }
    
    0 讨论(0)
  • 2021-01-04 07:14

    You just use

    delete layout;
    

    like you would with any other pointer you created using new.

    0 讨论(0)
  • 2021-01-04 07:35

    This code deletes the layout, all its children and everything inside the layout 'disappears'.

    qDeleteAll(yourWidget->findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly));
    delete layout();
    

    This deletes all direct widgets of the widget yourWidget. Using Qt::FindDirectChildrenOnly is essential as it prevents the deletion of widgets that are children of widgets that are also in the list and probably already deleted by the loop inside qDeleteAll.

    Here is the description of qDeleteAll:

    void qDeleteAll(ForwardIterator begin, ForwardIterator end)

    Deletes all the items in the range [begin, end] using the C++ delete > operator. The item type must be a pointer type (for example, QWidget *).

    Note that qDeleteAll needs to be called with a container from that widget (not the layout). And note that qDeleteAll does NOT delete yourWidget - just its children.

    Now a new layout can be set.

    0 讨论(0)
提交回复
热议问题