'Qt - Clear all widgets from inside a QWidget's layout
I have a QWidget in a dialog. Over the course of the program running, several QCheckBox * objects are added to the layout like this:
QCheckBox *c = new QCheckBox("Checkbox text");
ui->myWidget->layout()->addWidget(c);
This works fine for all the checkboxes. However, I also have a QPushButton called "clear" in my dialog, which when it is pressed should empty everything out of myWidget, leaving it blank like it was before any of the QCheckboxes were added. I've been looking around online and in the docs but I am having trouble finding a way to do this. I found this question which I thought was similar to my problem, and tried their solution like this:
void myClass::on_clear_clicked()
{
while(ui->myWidget->layout()->count() > 0)
{
QLayoutItem *item = ui->myWidget->layout()->takeAt(0);
delete item;
}
}
This however did not seem to do anything. It's worth noting that I'm not sure if this is translated from his answer correctly; it was a bit unclear how the function given should be implemented, so I made my best educated guess. If anyone knows what I can change in the above to make it work (or just a different way that would work), it would be greatly appreciated.
Solution 1:[1]
You can try this:
while ( QLayoutItem* item = ui->myWidget->layout()->takeAt( 0 ) )
{
Q_ASSERT( ! item->layout() ); // otherwise the layout will leak
delete item->widget();
delete item;
}
Solution 2:[2]
Given that you have a widget hierarchy consisting of cascaded layouts containing widgets then you should better go for the following.
Step 1: Delete all widgets
QList< QWidget* > children;
do
{
children = MYTOPWIDGET->findChildren< QWidget* >();
if ( children.count() == 0 )
break;
delete children.at( 0 );
}
while ( true );
Step 2: Delete all layouts
if ( MYTOPWIDGET->layout() )
{
QLayoutItem* p_item;
while ( ( p_item = MYTOPWIDGET->layout()->takeAt( 0 ) ) != nullptr )
delete p_item;
delete MYTOPWIDGET->layout();
}
After step 2 your MYTOPWIDGET should be clean.
Solution 3:[3]
PySide2 Solution:
from PySide2 import QtWidgets
def clearLayout(layout: QtWidgets.QLayout):
for i in reversed(range(layout.count())):
item = layout.itemAt(i)
if isinstance(item, QtWidgets.QLayout):
clearLayout(item)
elif item.widget():
item.widget().setParent(None)
else:
layout.removeItem(item)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kuba hasn't forgotten Monica |
| Solution 2 | boto |
| Solution 3 | BaiJiFeiLong |
