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关闭并释放资源

相关推荐
Algebraaaaa5 小时前
什么是前端、后端与全栈开发,Qt属于什么?
开发语言·前端·qt
大美B端工场-B端系统美颜师5 小时前
工控软件开发选择难?Electron、Qt、WPF 对比
qt·electron·wpf
QT 小鲜肉6 小时前
【个人成长笔记】Qt Creator快捷键终极指南:从入门到精通
开发语言·c++·笔记·qt·学习·学习方法
feiyangqingyun7 小时前
Qt项目作品在苹果macos上编译运行效果/视频监控系统/物联网平台等
开发语言·qt·macos
fsnine13 小时前
Python图形化界面——pyqt5教程
开发语言·python·qt
枫叶丹416 小时前
【Qt开发】多元素类控件(二)-> QTableWidget
开发语言·qt
syt_biancheng17 小时前
Qt--命名,快捷键及坐标系
开发语言·qt
江公望1 天前
Qt的环境变量QT_QPA_PLATFORM浅解
linux·qt
TNTLWT1 天前
Qt模型控件:QTreeView&QTreeWidget
qt
Larry_Yanan1 天前
QML学习笔记(四十三)QML与C++交互:上下文属性暴露
c++·笔记·qt·学习·ui·交互