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:

QLayoutItem *child;
  while ((child = layout->takeAt(0)) != 0) {
      ...
      delete child;
  }

方法一:

代码实现:

/清空horizontalLayout布局内的所有元素
QLayoutItem *child;
 while ((child = horizontalLayout->takeAt(0)) != 0)
 {
        //setParent为NULL,防止删除之后界面不消失
        if(child->widget())
        {
            child->widget()->setParent(NULL);
        }

        delete child;
 }

方法二:

代码实现

QList<SystemMenuButton*> btns = menulayout->findChildren<SystemMenuButton*>();//获取布局中所有按钮
    foreach (SystemMenuButton *btn, btns) {
        delete btn;    //析构所有按钮
    }


--------------------- 
作者:itas109 
来源:CSDN 
原文:https://blog.csdn.net/itas109/article/details/83181576 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 10
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值