Qt-正确动态删除布局中控件

使用布局控件的addWidget和removeWidget时,发现添加控件没有问题,但是却无法删除控件,删除后添加又出现了奇怪的错误布局,google后发现,removeWidget并不是删除控件

Removes the widget widget from the layout. After this call, it is the caller's responsibility to give the widget a reasonable geometry or to put the widget back into a layout or to explicitly hide it if necessary.

stackoverflow上对如何删除布局中控件的回答如下:

If you want to get rid of a widget completely, you only need to destruct it. You don't have to worry if it was in a layout. If the widget is dynamically allocated, then delete nsd is all you need, the layout->removeWidget call is not needed. You also don't have to give widgets any explicit parents - insertion into the layout will set proper parent.

正确做法是如果不需要该控件了可以直接delete它。

ui.verticalLayout_2->removeWidget(widget);
delete widget;

如果是删除布局内所有控件:

void UtilitiesTool::clearLayout(QLayout* layout)
{
    while (QLayoutItem* item = layout->takeAt(0))
    {
        if (QWidget* widget = item->widget())
            widget->deleteLater();

        if (QLayout* childLayout = item->layout())
            clearLayout(childLayout);

        if (QSpacerItem* spaerItem = item->spacerItem())
            layout->removeItem(spaerItem);

        delete item;
    }
}

参考:

1.https://stackoverflow.com/questions/37814292/qt-5-6-qvboxlayout-removewidget-then-addwidget-not-working-as-expected

2.https://forum.qt.io/topic/7834/problem-removing-widgets-from-a-layout/4


版权声明:本文为mrbone11原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。