Qt工作笔记-通过 对象树 或 delete this 释放对象
生活随笔
收集整理的這篇文章主要介紹了
Qt工作笔记-通过 对象树 或 delete this 释放对象
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
目錄
?
?
背景
實例
?
背景
今天在寫代碼的時候,new出的界面,沒有delete,因為是dialog,可以用exec() 把后面的界面阻塞掉,但個人并不喜歡這樣,畢竟覺得強扭的瓜不甜!不想讓后面的那個界面為了xxx而改變自己,所以在此,想用其他方法!Qt中一個局部對象,如何通過不在此函數(shù)中delete也能釋放!
?
經(jīng)過思考與實踐發(fā)現(xiàn)有2個方法:
1. 是使用Qt對象樹,這應(yīng)該是Qt上很常見的方法;
2. 是 delete this
?
實例
?
方法一:使用Qt的對象樹釋放!
當主界面被關(guān)閉后,會把對象樹上的釋放掉!
程序結(jié)構(gòu)如下:
?
源碼如下:
testdialog.h
#ifndef TESTDIALOG_H #define TESTDIALOG_H#include <QDialog>namespace Ui { class TestDialog; }class TestDialog : public QDialog {Q_OBJECTpublic:explicit TestDialog(QWidget *parent = 0);~TestDialog();protected slots:void btnClicked();protected:void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE;private:Ui::TestDialog *ui; };#endif // TESTDIALOG_Hwidget.h
#ifndef WIDGET_H #define WIDGET_H#include <QWidget>namespace Ui { class Widget; }class Widget : public QWidget {Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();protected slots:void btnClicke();private:Ui::Widget *ui; };#endif // WIDGET_Hmain.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中的析構(gòu)函數(shù)被調(diào)用"); }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();//不釋放,看看能不能析構(gòu) }testdialog.ui
widget.ui
?
第二種方法是delete this
把testdialog.cpp中btnclicked中的那兩行注釋去掉就可以了!
上面的這種只是一個例子,很脆弱,沒有考慮在棧區(qū)創(chuàng)建的對象!
?
?
總結(jié)
以上是生活随笔為你收集整理的Qt工作笔记-通过 对象树 或 delete this 释放对象的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt文档阅读笔记-QUdpSocket基
- 下一篇: Qt + Python + OpenCV