Question

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?

Was it helpful?

Solution

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().

OTHER TIPS

You should allow setting a parent
if you want to allow moving some object containing a member of type class A to another thread.
(Which you're not really able to prevent.)
In this case, the member A probably has to be moved, too.

From the docs:

A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. You can handle this event to perform any special processing. Note that any new events that are posted to this object will be handled in the targetThread.

So if you don't allow passing a parent, the maintainer of the object containing your class would have to override event(), check for QEvent::ThreadChange and move A manually.

From the docs:

A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. You can handle this event to perform any special processing. Note that any new events that are posted to this object will be handled in the targetThread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top