使用布局控件的addWidget和removeWidget时,发现添加控件没有问题,但是却无法删除控件,删除后添加又出现了奇怪的错误布局,google后发现,removeWidget并不是删除控件
Removes the widget widget from the layout. After this call, it is the caller's responsibility to give the widget a reasonable geometry or to put the widget back into a layout or to explicitly hide it if necessary.
stackoverflow上对如何删除布局中控件的回答如下:
If you want to get rid of a widget completely, you only need to destruct it. You don't have to worry if it was in a layout. If the widget is dynamically allocated, then
delete nsd
is all you need, thelayout->removeWidget
call is not needed. You also don't have to give widgets any explicit parents - insertion into the layout will set proper parent.
正确做法是如果不需要该控件了可以直接delete它。
ui.verticalLayout_2->removeWidget(widget);
delete widget;
如果是删除布局内所有控件:
void UtilitiesTool::clearLayout(QLayout* layout)
{
while (QLayoutItem* item = layout->takeAt(0))
{
if (QWidget* widget = item->widget())
widget->deleteLater();
if (QLayout* childLayout = item->layout())
clearLayout(childLayout);
if (QSpacerItem* spaerItem = item->spacerItem())
layout->removeItem(spaerItem);
delete item;
}
}
参考:
2.https://forum.qt.io/topic/7834/problem-removing-widgets-from-a-layout/4