Qt工作笔记-通过 对象树 或 delete this 释放对象

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/86598130

目录

 

 

背景

实例


 

背景

今天在写代码的时候,new出的界面,没有delete,因为是dialog,可以用exec() 把后面的界面阻塞掉,但个人并不喜欢这样,毕竟觉得强扭的瓜不甜!不想让后面的那个界面为了xxx而改变自己,所以在此,想用其他方法!Qt中一个局部对象,如何通过不在此函数中delete也能释放!

经过思考与实践发现有2个方法:

1. 是使用Qt对象树,这应该是Qt上很常见的方法;

2. 是 delete this

扫描二维码关注公众号,回复: 5095358 查看本文章

实例

方法一:使用Qt的对象树释放!

当主界面被关闭后,会把对象树上的释放掉!

程序结构如下:

源码如下:

testdialog.h

#ifndef TESTDIALOG_H
#define TESTDIALOG_H

#include <QDialog>

namespace Ui {
class TestDialog;
}

class TestDialog : public QDialog
{
    Q_OBJECT

public:
    explicit TestDialog(QWidget *parent = 0);
    ~TestDialog();

protected slots:
    void btnClicked();

protected:
    void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE;

private:
    Ui::TestDialog *ui;
};

#endif // TESTDIALOG_H

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

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

protected slots:
    void btnClicke();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

main.cpp

#include "widget.h"
#include <QApplication>

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

    return a.exec();
}

testdialog.cpp

#include "testdialog.h"
#include "ui_testdialog.h"

#include <QMessageBox>

TestDialog::TestDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TestDialog)
{
    ui->setupUi(this);

    connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(btnClicked()));
}

TestDialog::~TestDialog()
{
    delete ui;

    QMessageBox::information(this, "提示", "TestDialog中的析构函数被调用");
}

void TestDialog::btnClicked()
{
    //this->close();
    //delete this;
}

void TestDialog::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event)
    btnClicked();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include "testdialog.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(btnClicke()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::btnClicke()
{
    TestDialog *testDialog = new TestDialog(this);
    testDialog->show();

    //不释放,看看能不能析构
}

testdialog.ui

widget.ui

第二种方法是delete this

把testdialog.cpp中btnclicked中的那两行注释去掉就可以了!

上面的这种只是一个例子,很脆弱,没有考虑在栈区创建的对象!

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/86598130