Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 574
Toby Avatar asked Feb 12 '23 15:02

Toby


1 Answers

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.

like image 148
jpo38 Avatar answered Feb 14 '23 05:02

jpo38