Qt 对象树

一、什么是对象树

Qt中的对象树就是Qt中对象间的父子关系,每一个对象都有它所有子对象的指针,都有一个指向其父对象的指针。当创建对象在堆区时,如果指定的父亲是QObject派生下来的类或者是QObject的子类派生下来的类,当父对象被析构时子对象也会被析构。

二、示例

1.创建一个MyPushButton对象,继承QPushButton

 

2.在mypushbutton.cpp中对MyPushButton对象的构造和析构函数添加消息

#include "mypushbutton.h"
#include<QDebug>

MyPushButton::MyPushButton(QWidget *parent) : QPushButton(parent)
{
    qDebug()<<"MyPushButton构造调用";
}

MyPushButton::~MyPushButton()
{
    qDebug()<<"MyPushButton析构";
}

3.在主窗口创建MyPushButton按钮的实例

#include "mainwindow.h"
#include<QPushButton>
#include"mypushbutton.h"
#include<QtDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    
    MyPushButton *mybtn=new MyPushButton;
    mybtn->resize(120,50);
    mybtn->setText("MyPushButton");
    mybtn->move(200,0);
    mybtn->setParent(this);
}

MainWindow::~MainWindow()
{
}

 

4.在mainwindow.cpp中的MainWindow的析构函数里添加消息

MainWindow::~MainWindow()
{
    qDebug()<<"mainwindow析构";
}

5.关闭主窗口,查看各对象析构的顺序

MyPushButton构造调用
mainwindow析构 //此时只是走到析构函数里打印了mainwindow析构,mainwindow还没有被析构掉
MyPushButton析构

6.正确的顺序应该是:关闭主窗口时,主窗口的析构函数被调用,然后主窗口会看自己有没有子对象,有的话先把他们析构了,最后再把自己析构。

 

posted @ 2020-12-19 14:34  sxkio  阅读(876)  评论(0编辑  收藏  举报