Re-populating a layout's widgets
-
I want to say to all of you many thanks for helping me get up to speed on Qt. I am about 7 years late it seems.
All of the docs and the many topics I've read say to do this if I want to repop a layout. I must first remove the ones currently in place:
while ( m_pane->count() != 0 ) { item = m_pane->itemAt(0); if ( item->widget() ) { delete item->widget(); //delete item; } }
But this code only runs if the "delete item" call is remarked out. If an attempt is made to delete the item, the application crashes. Strangely, it works fine without deleting the item, but I suspect that tiny amounts of memory are being leaked, not sure. Has the behavior been changed? Do I need to disconnect the slot and context menu attached to them?
-
I want to say to all of you many thanks for helping me get up to speed on Qt. I am about 7 years late it seems.
All of the docs and the many topics I've read say to do this if I want to repop a layout. I must first remove the ones currently in place:
while ( m_pane->count() != 0 ) { item = m_pane->itemAt(0); if ( item->widget() ) { delete item->widget(); //delete item; } }
But this code only runs if the "delete item" call is remarked out. If an attempt is made to delete the item, the application crashes. Strangely, it works fine without deleting the item, but I suspect that tiny amounts of memory are being leaked, not sure. Has the behavior been changed? Do I need to disconnect the slot and context menu attached to them?
@CJF-the-Elder said in Re-populating a layout's widgets:
I suspect that tiny amounts of memory are being leaked, not sure.
Not if your
item
has aQObject
parent.Has the behavior been changed?
No.
Do I need to disconnect the slot and context menu attached to them?
Also no.
A cleaner and working solution is even listed in the Qt Documentation:
QLayout::takeAt(int index)
is the key.QLayoutItem *child; while ((child = layout->takeAt(0)) != nullptr) { ... delete child->widget(); // delete the widget delete child; // delete the layout item }
-
Thanks, that fixed it. And thanks for insisting I try something that didn't work for me prior. When I first tried the code from the doc as you show, I must have been doing something else wrong.
-
-
Hi,
Depending on the complexity of your layout it might also be worth considering putting "grouped widgets" in their own QWidget subclass to simplify these kind of loops.
-
Suggestion duly noted. Since the widget(s) the code was adding and removing was the first QWidget I ever wrote, it definitely needs revisiting.