How to delete an already existing layout on a widget?

蹲街弑〆低调 提交于 2019-12-18 19:16:21

问题


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

from http://doc.qt.io/qt-5.9/qwidget.html#setLayout

Which function is used for deleting the previous layout?


回答1:


You just use

delete layout;

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




回答2:


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;



回答3:


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;
    }
}



回答4:


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.



来源:https://stackoverflow.com/questions/7528680/how-to-delete-an-already-existing-layout-on-a-widget

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!