I've been reading up on the ownership of Qwidgets and deleting them. eg: http://qt-project.org/doc/qt-4.8/objecttrees.html
This says "You can also delete child objects yourself, and they will remove themselves from their parents"
However a lot of examples I have seen set the parent to null before deleting it. eg:
if (widget != NULL)
{
layout->removeWidget(widget);
widget->setParent(NULL);
delete widget;
}
Is there any need for the setParent(NULL);
?
Leading on from this, is there any reason why I cannot just do a
delete layout->itemAt(i);
or
delete layout->takeAt(i);
In fact, is there any real difference between these last two? I am assuming all my objects are on the heap of course.
There is definitely no need to set widget's parent to NULL
before deleting it. Child widget will automatically unregister from its parent upon deletion.
For your second question, real difference between itemAt
and takeAt
is that itemAt
returns the specified layout item, takeAt
returns it too but additionaly removes it from the layout.
Using takeAt
changes the layout item count because it removed the returned item from the layout. So be careful, don't use it in a loop like for ( int i = 0; i != layout->count(); ++i )
because you'll end up with i being greater than current layout->count()
...
Note that doing delete layout->itemAt(i);
does not automatically remove the deleted item from the layout, so this must be avoided.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With