对象树 概念:各个窗口对象通过建立父子关系构造对的一个关系树 内存管理: 父对象释放的时候会自动释放各个子对象 (使用children列表) 以后基本都是用new的方式来创建窗口对象 注意点: 1 父对象能够被释放 2 父对象、子对象,直接或者间接继承自QObject
#include "widget.h"
#include "ui_widget.h"
#include <QPushButton>
#include "mypushbutton.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//局部变量在函数退出的时候就会自动释放
// QPushButton btn("按钮1",this);
// btn.show();
/* 解决 让按钮的生命周期长一点
* 1 static
* 2 类成员变量
* 3 new 一个 动态内存分配对象
*/
MyPushButton *btn1 = new MyPushButton(this);
btn1->setText("按钮1");
//没有delete
//验证析构
//再继承一个按钮类,在子类的析构函数里边打log
}
Widget::~Widget()
{
delete ui;
}
//mypushbutton
#ifndef MYPUSHBUTTON_H
#define MYPUSHBUTTON_H
#include <QWidget>
#include <QPushButton>
class MyPushButton : public QPushButton //继承自QPushButton
{
Q_OBJECT
public:
explicit MyPushButton(QWidget *parent = nullptr);
~MyPushButton();
signals:
};
#endif // MYPUSHBUTTON_H
#include "mypushbutton.h"
#include <QDebug>
MyPushButton::MyPushButton(QWidget *parent)
: QPushButton{parent}
{}
MyPushButton::~MyPushButton()
{
qDebug()<<"MypushButton Destoryed";
}
标签:Widget,parent,对象,MyPushButton,QPushButton,include
From: https://www.cnblogs.com/lambdaios/p/17975736