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:
- 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...
- 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.