Do QObject derived types need a parent QObject?

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

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

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

 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, if I have a default value (0), or I don't have one?

+4
source share
2 answers

As such, you do not need a parent.

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

If you set the parent, and then when the parent is deleted, it will also delete all its children.

Following an excerpt from the doc :

QObjects are organized in object trees. When you create a QObject with another object as a parent, the object will automatically add itself to the children () parent list. The parent takes responsibility for the object; that is, it automatically removes its children in its destructor. You can search for an object by name and, if necessary, with findChild () or findChildren ().

+8
source

You must allow the installation of the parent object if you want to allow the movement of an object containing an element of type class A to another stream.
(Which you really cannot prevent.)
In this case, probably, element A should also be moved.

From docs :

The QEvent :: ThreadChange event is dispatched to this object immediately before the thread affinity changes. You can handle this event to perform any special processing. Note that any new events that are dispatched to this object will be processed in targetThread.

So, if you do not allow the parent to be passed, then the supporting object containing your class will have to override event() , check for QEvent::ThreadChange and manually move it.

From docs :

The QEvent :: ThreadChange event is dispatched to this object immediately before the thread affinity changes. You can handle this event to perform any special processing. Note that any new events that are dispatched to this object will be processed in targetThread.

0
source

Source: https://habr.com/ru/post/1483086/


All Articles