1.Qt对象间可以存在父子关系
每一个对象都保存有它所有子对象的指针
每一个对象都有一个指向其父对象的指针
2.当指定Qt对象的父对象时
其父对象会在子对象链表中加入该对象的指针
该对象会保存指向其父对象的指针
QObject* p = new QObject();
QObject* c1 = new QObject();
QObject* c2 = new QObject();
c1->setParent(p);
c2->setParent(p);
编程实验:对象间的父子关系
#include <QCoreApplication>
#include <QDebug>
void fcTest()
{
QObject* p = new QObject();
QObject* c1 = new QObject();
QObject* c2 = new QObject();
c1->setParent(p);
c2->setParent(p);
qDebug() << "c1:" << c1;
qDebug() << "c2:" << c2;
const QObjectList& list = p->children();
for(int i = 0; i < list.length(); i++)
{
qDebug() << list[i];
}
qDebug() << "p:" <<p;
qDebug() << "c1 parent:" << c1->parent();
qDebug() << "c2 parent:" << c2->parent();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
fcTest();
return a.exec();
}
3.Qt对象被销毁时
将自己从父对象的Children List移除
将自己的Children List中的所有对象销毁
注意:使用Qt开发时,不仅要时刻注意内存泄漏的问题,还要时刻关注对象是否可能被多次销毁的问题
利用Qt对象间的父子关系可以构成对象树
删除树中的节点时会导致对应的子树被销毁
编程实验:对象的删除delTest()
#include <QCoreApplication>
#include <QDebug>
class MObj : public QObject
{
QString m_name;
public:
MObj(const QString& name)
{
m_name = name;
qDebug() << "Constructor: " << m_name;
}
~MObj()
{
qDebug() << "Destructor: " << m_name;
}
};
void fcTest()
{
QObject* p = new QObject();
QObject* c1 = new QObject();
QObject* c2 = new QObject();
c1->setParent(p);
c2->setParent(p);
qDebug() << "c1:" << c1;
qDebug() << "c2:" << c2;
const QObjectList& list = p->children();
for(int i = 0; i < list.length(); i++)
{
qDebug() << list[i];
}
qDebug() << "p:" <<p;
qDebug() << "c1 parent:" << c1->parent();
qDebug() << "c2 parent:" << c2->parent();
}
void delTest()
{
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;
//delete obj4; //运行出错,obj4已经被销毁了,不能二次销毁
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
fcTest();
delTest();
return a.exec();
}
小结:
(1)Qt对象间可以存在父子关系
(2)通过父子关系能够得到Qt对象树
(3)Qt对象销毁时解除和父对象间的父子关系
(4)Qt对象销毁时将同样销毁所有的子对象