Friday, 26 August 2011

Dynamically removing QWidgets from a QLayout

I’ve seen some strange things when trying to remove QWidgets from a QLayout while using code such as:

MyWidget->layout()->removeWidget(AnotherWidget);

Sometimes AnotherWidget wouldn’t be removed, sometimes it would display only part of it.

After a bit of searching I came across a different solution that worked a treat. The below code removes all widgets MyWidget’s layout.


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

And if you wanted to only remove a single widget from the layout:

while((QLayoutItem *child = MyWidget->layout()->takeAt(0)) != 0)
{
if(child == AnotherWidget)
{
delete child->widget();
delete child;
}
}

No comments:

Post a Comment