Qt 的 QLayout 文檔里是這么寫的,但其實不完整,參看我最下面的代碼。
[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;
}
-----------正確方式--------
QLayoutItem *child;
while ((child = layout->takeAt(0)) != 0)
{
layout->removeWidget(child->widget());
child->widget()->setParent(0);
delete child;
}