Qt 清空layout中所有控件

layout中的控件可以通过addWidget添加。但是有个问题:增加之后如何将控件删除呢,并且使其立即生效是一个问题。

实现方法:

QWidget有一个setParent方法,当setParent(NULL)时,就会使其不在相应的界面上显示。如果不设置,即便删除了layout,QWidget还是会显示在界面上。

void QWidget::setParent(QWidget *parent)

Sets the parent of the widget to parent, and resets the window flags. The widget is moved to position (0, 0) in its new parent.

If the new parent widget is in a different window, the reparented widget and its children are appended to the end of the tab chain of the new parent widget, in the same internal order as before. If one of the moved widgets had keyboard focus, setParent() calls clearFocus() for that widget.

If the new parent widget is in the same window as the old parent, setting the parent doesn't change the tab order or keyboard focus.

If the "new" parent widget is the old parent widget, this function does nothing.

Note: The widget becomes invisible as part of changing its parent, even if it was previously visible. You must call show() to make the widget visible again.

Warning: It is very unlikely that you will ever need this function. If you have a widget that changes its content dynamically, it is far easier to use QStackedWidget.

[pure virtual] QLayoutItem *QLayout::takeAt(int index)

Must be implemented in subclasses to remove the layout item at index from the layout, and return the item. If there is no such item, the function must do nothing and return 0. Items are numbered consecutively from 0. If an item is removed, other items will be renumbered.

The following code fragment shows a safe way to remove all items from a layout:

1 QLayoutItem *child;
2   while ((child = layout->takeAt(0)) != 0) {
3       ...
4       delete child;
5   }

 方法一:

代码实现:

 1 //清空horizontalLayout布局内的所有元素
 2 QLayoutItem *child;
 3  while ((child = horizontalLayout->takeAt(0)) != 0)
 4  {
 5         //setParent为NULL,防止删除之后界面不消失
 6         if(child->widget())
 7         {
 8             child->widget()->setParent(NULL);
 9         }
10  
11         delete child;
12  }

方法二:

代码实现

1 QList<SystemMenuButton*> btns = menulayout->findChildren<SystemMenuButton*>();//获取布局中所有按钮
2     foreach (SystemMenuButton *btn, btns) {
3         delete btn;    //析构所有按钮
4     }
原文地址:https://www.cnblogs.com/ybqjymy/p/13840363.html