Qt; QWidget removal and deletion. setParent(NULL) necessary?
Asked Answered
P

1

5

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.

Presentment answered 8/11, 2014 at 12:32 Comment(0)
S
9

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.

Spruce answered 8/11, 2014 at 12:43 Comment(1)
Excellent, that confirms what I was thinking. I'll avoid the delete layout->itemAt(i) if it cannot be trusted with testing. Thanks!Presentment

© 2022 - 2024 — McMap. All rights reserved.