I have a layout (containing QLabels and QSpacers) set on a button and I want to replace this with a new one. To do this I have made the following code:
while(!layout.isEmpty())
{
delete(layout.takeAt(0));
}
After this I set the new layout:
layout.addWidget(...)
layout.addSpacer(...)
...
button.setLayout(layout)
Unfortunately the new layout is set, but the old one can still be seen. How do I solve this?
Based on your comments, you want to delete the items in the widget, not the layout.
QLayout::takeAtreturns aQLayoutItem*. Thus, you are looping through the widget’s layout and deleting the layout items, but not the widgets that were added to the layout items. As a test, you might try the following instead:However, this isn’t what I would consider a good long-term design. There may be a few special cases where this is the best method, but I would recommend looking into using a stacked widget or something similar to switch back and forth between the widgets presented, rather than destroy and recreate a whole array of widgets in a button. Alternately, consider two different buttons, and destroy and reinsert just the button rather than the contents of the button.