Important: Please read the Qt Code of Conduct -

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, since MainWindow inherits from a QMainWindow who inherits from QWidget, then my QGraphicsScene should be automatically deallocated since it is a child of QMainWindow. Does it work like this for every object inside a QWidget? 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);

  • Lifetime Qt Champion


    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 
        Object(QWidget* parent = 0);
        QWidget* parent;
    Object::Object(QWidget* parent) :

    And then declare a new object in this way?

    Object* obj = new Object(this);

  • Moderators

    Unfortunately, no. To make use of the parent-child mechanism your object must derive from QObject at least. Search through the forum for "QObject" and "RAII", Here is a thread where I've put some effort in explaining the QObject ownership. Back to your question:

    class Object : public QObject
        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.