疑惑
为什么在析构的时候是实例化的窗口(widget)先析构再是控件析构?不应该是控件作为窗口的属性应当先被析构吗?
源代码
- 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
- 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
- mtbutton.cpp
#include "mybutton.h"
#include<QDebug>
myButton::myButton(QWidget *parent) : QPushButton(parent)
{
qDebug()<<"myButton"<<endl;
}
myButton::~myButton(){
qDebug()<<"~myButton";
}
- 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()<<"窗口销毁";
}
- main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
- 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