Do QObject derived types need a parent QObject?

Ferenc Deak picture Ferenc Deak · May 28, 2013 · Viewed 7.5k times · Source

I am writing some Qt class which is derived from QObject, it looks like:

class A : public QObject
{
    Q_OBJECT
public: A() : QObject() {}
.....
}

but in several places I saw, that the QObject derived classes all have a parent, like:

class A : public QObject
{
    Q_OBJECT
public: A(QObject* parent = 0) : QObject(parent) {}
.....
}

So the question is: do I need a parent or not? What is the difference if I have one, if I have a default one (0) or I don't have at all?

Answer

Kunal picture Kunal · May 28, 2013

As such you don't need a parent.

But setting parent has some advantage in terms of garbage collection.

If you set a parent then when parent gets deleted, it will also delete all its children.

Following excerpt from the doc:

QObjects organize themselves in object trees. When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild() or findChildren().