Search code examples
qtmemory-managementmemory-leaksparent-childnew-operator

Issue regarding setting parent of widget in Qt


From this post here, in general:

All QObjects will delete their own child objects automatically. (See docs here.) QWidgets are QObjects. So as long as you establish a parent/child relationship, you do not need to manually delete your objects. To do that, simply pass a pointer to the parent object to the constructor:

QLabel *label1 = new QLabel;   // <<- NEED TO DELETE
QLabel *label2 = new QLabel(some_parent_obj);   // Will be deleted when some_parent_obj is deleted

So some questions arises:

  1. Does every widget necessary needed/required a parent? If no, what are the exceptions? If yes, what happens to widgets without parent?

I asked this because from examples in Qt Docs, some example widgets have parents (QLabel example) but some doesn't (QBarChart example, and also QFont, QColor, etc...).

So I'm wondering if there's an exception, or those widgets just don't need any parents, or if I declare them with new for some reason, I have to delete afterward.

And vice versa...

  1. Does a widget without parent guarantee to cause a memory leak (or something similar) when the widget which it stays in (not necessary its parent) is deleted? Or if it's removed from a layout without any deletion happening?

Because from my experience with my code, I've created probably quite a lot (~100) of widgets and other stuffs without neither setting any parent (nor using delete afterward), and the project appears to run fine without any stalls even after a while (the effect might be underlying though, as I haven't run Memcheck), hence this question is here.


Solution

  • Does every widget necessary needed/required a parent?

    If you want them to be deleted automatically - yes. But...

    If no, what are the exceptions? If yes, what happens to widgets without parent?

    You do not need to provide a parent to widget if you attach it to layout using QLayout::addWidget. If you look into source code, you'll see that when you do so, it automatically attaches layout's parent as widget's parent(unless you didn't attach layout to any widget).

    But if you leave the widget created with new without parent and do not attach to anything - it is leaking memory. You must delete it either using delete or QObject::deleteLater. The last option is recommended when object has any connections.

    Does a widget without parent guarantee to cause a memory leak (or something similar) when the widget which it stays in (not necessary its parent) is deleted? Or if it's removed from a layout without any deletion happening?

    As I already mention QLayout::addWidget sets parent for added widget, so the answer is no. Also note, that when you call QLayout::removeWidget, it removes only QLayoutItem from layout, but widget's parent stays the same as it was after calling QLayout::addWidget.