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     }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM