对Qt对象树析构顺序的疑惑(已解决)

疑惑

为什么在析构的时候是实例化的窗口(widget)先析构再是控件析构?不应该是控件作为窗口的属性应当先被析构吗?

源代码

  1. mybutton.h
#ifndef MYBUTTON_H
#define MYBUTTON_H

#include <QWidget>
#include<QPushButton>

class myButton : public QPushButton
{
    Q_OBJECT
public:
    explicit myButton(QWidget *parent = nullptr);
    ~myButton();
signals:

public slots:
};

#endif // MYBUTTON_H
  1. widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include<QPushButton>
#include<mybutton.h>
#include <QWidget>
#include<QDebug>

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();
};

#endif // WIDGET_H
  1. mtbutton.cpp
#include "mybutton.h"
#include<QDebug>

myButton::myButton(QWidget *parent) : QPushButton(parent)
{
    qDebug()<<"myButton"<<endl;
}

myButton::~myButton(){
    qDebug()<<"~myButton";
}
  1. widgeh.cpp
#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    qDebug()<<"窗口创建"<<endl;

    myButton *button = new myButton;
    button->setParent(this);
    button->setText("自定义按钮");
}

Widget::~Widget()
{
    qDebug()<<"窗口销毁";
}
  1. main.cpp
#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}
  1. pro文件
#-------------------------------------------------
#
# Project created by QtCreator 2023-03-16T20:32:05
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = 02_study_button
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += \
        main.cpp \
        widget.cpp \
    mybutton.cpp

HEADERS += \
        widget.h \
    mybutton.h

源代码的运行情况

在这里插入图片描述
从这里很明显可以看到析构的顺序是先析构窗口再析构button

总结(问题原因)

这其实是析构函数的特殊情况:当A类作为B类的成员时,析构的顺序为->先析构B,再析构A

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默示MoS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值