Search code examples
c++qtmember-variables

Parent-child relationship set to member variables in Qt


I was reading Qt Documentation here. I found the following sentence under the title 'Thread Affinity'.

Note: A QObject's member variables do not automatically become its children. The parent-child relationship must be set by either passing a pointer to the child's constructor, or by calling setParent().

I don't understand what it mentioned as set parent-child relationship between object and it's member variables. I only know the parent-child relationship between super class and sub class.

Can anyone explain this sentence to me? If you can provide a example it is more helpful.

Thanks for reading.


Solution

  • Member variables will NOT become child objects without explicitly setting parent property. A Object subclass normally takes another QObject as it's parent in the constructor.

    class Test : public QObject
    {
      Q_OBJECT
      public:
        Test(QObject* prnt) 
          : QObject(prnt),
            timerNoPrnt(), // Test object is NOT the parent. This won't be deleted when Test object gets deleted.
            timer(this)    // Test object is the parent here. This will be deleted when Test object gets deleted. 
        {
          timerNoPrnt->setParent(this); // now parent assigned.
        }
      private:
        QTimer*           timerNoPrnt;   // member variable
        QTimer*           timer;
    }