Qt - remove all widgets from layout?

前端 未结 12 650
野性不改
野性不改 2020-12-01 01:33

This doesn\'t seem easy. Basically, I add QPushButtons through a function to a layout, and when the function executes, I want to clear the layout first (removi

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 02:21

    None of the existing answers worked in my application. A modification to Darko Maksimovic's appears to work, so far. Here it is:

    void clearLayout(QLayout* layout, bool deleteWidgets = true)
    {
        while (QLayoutItem* item = layout->takeAt(0))
        {
            QWidget* widget;
            if (  (deleteWidgets)
                  && (widget = item->widget())  ) {
                delete widget;
            }
            if (QLayout* childLayout = item->layout()) {
                clearLayout(childLayout, deleteWidgets);
            }
            delete item;
        }
    }
    

    It was necessary, at least with my hierarchy of widgets and layouts, to recurse and to delete widgets explicity.

提交回复
热议问题