QWidget's children destruction mechanism
-
I wrote a very big application, consisting of many classes, custom classes, etc.
Now, since many object gets dynamically allocated onto the heap, of course I need to deallocate them in the destructors.Here is reported that, in the
QWidget
's destructor, all [...] widget's children are deleted first. The application exits if this widget is the main widget. So, sinceMainWindow
inherits from aQMainWindow
who inherits fromQWidget
, then myQGraphicsScene
should be automatically deallocated since it is a child ofQMainWindow
. Does it work like this for every object inside aQWidget
? Have I to specify a parent for the object in order to be sure it gets deleted when the parent's destructor gets called?
If I create a new object like this:Object* obj = new Object;
Does it get deleted in the parent destructor even if no parent has been specified?
Or shall I declare it like this?Object* obj = new Object(this);
-
Hi,
It works like this for objects with a parent and for widgets put in a layout that has been set on a widget (this will trigger the parenting)
If you don't specify any parent then no, it won't be deleted automatically. Depending on your object needs you can also make use of smart pointers like QScopedPointer.
-
@SGaist so if I want to define a custom object, is it enough to have something like this?
class Object { public: Object(QWidget* parent = 0); private: QWidget* parent; } Object::Object(QWidget* parent) : parent(parent) {}
And then declare a new object in this way?
Object* obj = new Object(this);
-
@alogim
Hello,
Unfortunately, no. To make use of the parent-child mechanism your object must derive fromQObject
at least.Search through the forum for "QObject" and "RAII",Here is a thread where I've put some effort in explaining theQObject
ownership. Back to your question:class Object : public QObject { public: Object(QWidget * parent = 0) : QObject(parent) { } };
Will do what you want, i.e. delete the
Object
when the parent is destroyed. Then you indeed create your object like this:Object * obj = new Object(this);
and it's sufficient to ensure proper cleanup.
Kind regards.