Reputation: 5377
I have an interface in Qt 4.7 that I'm having a little difficulty getting to behave as I'd like.
Basic Description of Desired Behaviour: user makes a selection in a combo box, which causes a query to go to another function which returns a QHBoxLayout object that generally includes several labels, line edits, etc. This will adjust the contents of a layout on the interface to remove the previous selection, and add the new details.
What's Actually Happening: The new layout is appearing, but the old one remains also, so they draw on top of each other resulting in a mess.
This is the code I have for the slot that the currentIndexChanged signal is linked to:
void updateAxisLabels(const QString & value)
{
if ( m_current != "" )
{
QHBoxLayout* xOld = m_transforms[m_current]->xAxis();
m_uiForm.layoutXAxis->removeItem(m_transforms[m_current]->xAxis());
delete m_transforms[m_current]->xAxis();
m_transforms[m_current]->init();
}
m_uiForm.layoutXAxis->addLayout(m_transforms[value]->xAxis());
m_current = value;
m_uiForm.layoutXAxis->update();
}
Here m_transforms is a map linking the contents of the combo box to an object with the xAxis() function (returning a QHBoxLayout*), and an init() function which will re-create the layout when it's been deleted. m_current is just a QString that I'm using to tell me which one I need to remove.
Reason I'm deleting it: because this is what half an hour of googling led me to believe was the right thing to do.
Any help much appreciated. :)
Upvotes: 0
Views: 592
Reputation: 8958
I've done this kind of thing before, and you definitely have not only remove the widget from the layout but also delete it.
Normally when I do this I create a layout especially for hosting my widget. So that I can just delete everything from inside the layout, and not have to worry about anything else that might be in there.
Here is the recommended way to loop through all the items in a layout and remove them.
QLayoutItem *child;
while ((child = m_uiForm.layoutXAxis->takeAt(0)) != 0)
{
delete child;
}
So then you can call any cleanup you want to do before it gets deleted.
You can also call layout->removeWidget(your widget) or layout->removeItem(layout) to remove one specific thing from a layout. But you have to be careful with this. The doc says:
Removes the 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.
So you want to make sure you also delete the widget afterwards to make sure that it doesn't show anywhere.
However, the other problem with this approach is if the widget/layout you are inserting/removing is somewhere in the middle of a bunch of other widgets in your layout, then you will have a lot of fun trying to replace it in the correct location.
Which is why I usually try to create a layout specifically for this purpose with nothing else in it.
Upvotes: 2