Qt - Clear all widgets from inside a QWidget's layout

前端 未结 3 1347
悲&欢浪女
悲&欢浪女 2021-01-12 02:18

I have a QWidget in a dialog. Over the course of the program running, several QCheckBox * objects are added to the layout like this:



        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 02:38

    The wonderful thing about layouts is that they handle a deletion of a widget automatically. So all you really need is to iterate over the widgets and you're done. Since you want to wipe out all children of a given widget, simply do:

    for (auto widget: ui->myWidget::findChildren
                                                ({}, Qt::FindDirectChildrenOnly))
      delete widget;
    

    No need to worry about layouts at all. This works whether the children were managed by a layout or not.

    If you want to be really correct, you would need to ignore the widgets that are child widgets but are stand-alone windows. This would be the case if this was in general-purpose library code:

    for (auto widget: ui->myWidget::findChildren
                                                ({}, Qt::FindDirectChildrenOnly)) 
      if (! widget->windowFlags() & Qt::Window) delete widget;
    

    Alternatively, if you only want to delete the children managed by a given layout and its sublayouts:

    void clearWidgets(QLayout * layout) {
       if (! layout)
          return;
       while (auto item = layout->takeAt(0)) {
          delete item->widget();
          clearWidgets(item->layout());
       }
    }
    

提交回复
热议问题