A parent-child relationship can exist between Qt objects
Objects that inherit from the QObject class or its subclasses are called Qt objects.
When specifying the parent of a Qt object
- You need to set the parent-child relationship between objects through the setParent() member function
- The child object will save its own pointer address in the children List list of the parent object (because the parent object can have multiple child objects)
- There will be a pointer to its parent object inside the child object, which can be viewed through the parent () member function
code experiment
Functions that need to be used:
void QObject::setParent ( QObject * parent ); // Set the parent object as its own parent object const QObjectList & QObject::children (); // Return a QObjectList (child object linked list), which stores the address of the child object. QObject * QObject::parent (); // Return a pointer to the parent object
code show as below:
#include <QtCore/QCoreApplication> #include <QDebug> class MObj : public QObject { }; void func() { MObj *obj1 = new MObj; MObj *obj2 = new MObj; MObj *obj3 = new MObj; qDebug()<<"obj1 ="<<obj1; qDebug()<<"obj2 ="<<obj2; qDebug()<<"obj3 ="<<obj3; qDebug(); obj2 ->setParent(obj1); // Set obj1 as the parent object of obj2 obj3 ->setParent(obj1); // Set obj1 as the parent object of obj3 const QObjectList& list =obj1->children(); //获取obj1 的children list for(int i=0; i<list.length();i++) { qDebug()<<"children list:"<<list[i]<<endl; } qDebug()<<"obj2 parent:"<<obj2->parent(); qDebug()<<"obj3 parent:"<<obj3->parent(); } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); func(); return a.exec(); }
run print:
When a Qt object is destroyed
- Remove your own address from the parent object's linked list children List
- Destroy (delete) all child objects in its own child object linked list children Li s t
Therefore, when deleting a Qt object, you also need to pay attention to whether it has child objects, as shown in the following figure:
code test delete
code show as below:
#include <QDebug> #include <QString> class MObj : public QObject { private: QString mvalue; public: MObj(QString i=0):mvalue(i) {} ~MObj() { qDebug()<<"~Mobj : "<<mvalue; } }; void func() { MObj *obj1 = new MObj("obj1"); MObj *obj2 = new MObj("obj2"); MObj *obj3 = new MObj("obj3"); MObj *obj4 = new MObj("obj4"); obj2->setParent(obj1); obj3->setParent(obj1); obj4->setParent(obj3); delete obj3; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); func(); return a.exec(); }
run print: