If I subclassed any widget the usual pattern is:
ZTabWidget::ZTabWidget(QWidget *parent):QTabWidget(parent){
blah ... blah ...
}
The usual pattern is:
WidgetB widgetb = new WidgetB(widgeta)
widgeta.addWidget(widgetb);
Is there any harm in having all my widgets assigned MainWindow as their respective parent – even though, following the trails of addWidget hierarchy, most of those widgets have another widget as the addWidget parent:
WidgetB widgetb = new WidgetB(mainWindow)
widgeta.addWidget(widgetb);
The reason I wish to do this is because mainWindow holds all the main items of the application and that I could have my any of my subclassed widgets reference those items.
In fact, I am thinking of a proxy widget that is merely used to hold some common references and use that proxy widget as the common parent of all my widgets. Any problem in that?
Exactly, what is the use of having registered a parent for a QWidget? Is the parent even used internally?
Does the addWidget parent have to be the same as the constructor parent?
There are actually two aspects two your questions:
Memory management
The tree-like organization of
QWidgets(and in fact of anyQObjects) is part of the memory management strategy used within the Qt-Framework. Assigning aQObjectto a parent means that ownership of the child object is transferred to the parent object. If the parent is deleted, all its children are also deleted. From the docs:This means you can organize your widgets in any way that seems sensible to you (as long as you don’t introduce memory leaks). I think, however, that it is a common practice to assign all the widgets to their respective container (either explicitly, or better, using methods like
addWidget).If a widget is assigned to a
QLayoutusingaddWidget, then ownership of the widget is transferred to the layout (which in turn is probably owned by another surrounding layout or the main window). So yes, the relationship defined by this method includes the more general parent-child relationship described above.Now, as soon as the main window gets destroyed, basically the whole tree of
QObjectsis deleted as you’d expect.Consequently, if you leave an object “parentless”, it is your own responsibility to delete it.
GUI semantics
As Frank noted correctly, in some contexts the parent-child relationship between
QWidgetsalso bears a semantically meaning to the GUI framework. An example of this are modal dialogs, who block their parent as long as they stay open.