Qt 窗口可见性 之 工程案例

工程网盘url:https://pan.baidu.com/s/1jl1xwxVg4ft0foUZGUM9rQ

提取码: dk9n

工程核心代码:

cpp 复制代码
/* widgetcloseandhide.cpp */

#include <QDebug>           //"qDebug打印"头文件
#include "widgetcloseandhide.h"
#include "ui_widgetcloseandhide.h"

WidgetCloseAndHide::WidgetCloseAndHide(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::WidgetCloseAndHide)
{
    ui->setupUi(this);
    m_pFormChild = new FormChild;
}

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

void WidgetCloseAndHide::on_pushButton_open_clicked()
{
    qDebug() << "open ===> child form";
    if(m_pFormChild != nullptr) m_pFormChild->show();
}

void WidgetCloseAndHide::on_pushButton_close_clicked()
{
    qDebug() << "close ===> child form";
    if(m_pFormChild != nullptr) m_pFormChild->close();
    //qDebug() << "hide ===> child form";
    //if(m_pFormChild != nullptr) m_pFormChild->hide();
}
cpp 复制代码
/* formchild.cpp */

#include "formchild.h"
#include "ui_formchild.h"

#include <QDebug>           //"qDebug打印"头文件
#include <QCloseEvent>      //"关闭事件类型"头文件

FormChild::FormChild(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormChild)
{
    ui->setupUi(this);
    this->setAttribute(Qt::WA_DeleteOnClose, true);//设置属性:当窗口收到close信号时,释放资源
}

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

void FormChild::closeEvent(QCloseEvent *event)
{
    //qDebug() << "do closeEvent, but ignore";
    //event->ignore();//若不希望子窗口被关闭

    qDebug() << "do closeEvent and delete it";
    event->accept();//默认允许窗口关闭,有无此语句都可以
}

结论1:当重写了closeEvent方法后,窗口菜单栏的"关闭按钮×"也按照重写的方法执行(重写的方法优先级高)

Qt close关闭窗口

结论2:hide隐藏窗口并不是最小化窗口;hide函数不会触发任何关闭事件(如closeEvent);窗口菜单栏的"关闭按钮×"触发了closeEvent,但事件被忽略了,故窗口不会关闭。

Qt hide隐藏窗口

结论3:当子窗口设置了属性 setAttribute(Qt::WA_DeleteOnClose, true)后,close关闭窗口时会释放其资源,若想再次show该子窗口,需要重新new或者重启程序,否则程序崩溃。

Qt close关闭并释放资源

相关推荐
blasit13 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
范特西.i6 天前
QT聊天项目(8)
开发语言·qt
枫叶丹46 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
十五年专注C++开发6 天前
Qt deleteLater作用及源码分析
开发语言·c++·qt·qobject
kangzerun6 天前
SQLiteManager:一个优雅的Qt SQLite数据库操作类
数据库·qt·sqlite
金刚狼886 天前
qt和qt creator的下载安装
开发语言·qt
追烽少年x6 天前
Qt中使用Zint库显示二维码
qt
谁刺我心6 天前
qt源码、qt在线安装器镜像下载
开发语言·qt
金刚狼886 天前
在qt creator中创建helloworld程序并构建
开发语言·qt
扶尔魔ocy7 天前
【转载】QT使用linuxdeployqt打包
开发语言·qt