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

相关推荐
MeowKnight95812 小时前
【Qt】Qt实践记录2——TCP通信服务器和客户端demo
笔记·qt
Larry_Yanan19 小时前
QML学习笔记(五十二)QML与C++交互:数据转换——时间和日期
开发语言·c++·笔记·qt·学习·ui·交互
十启树1 天前
Qt 中实现炫酷的开机启动动画
qt
一叶之秋14122 天前
QT背景介绍与环境搭建
开发语言·qt
QT 小鲜肉2 天前
【QT/C++】Qt网络编程进阶:UDP通信和HTTP请求的基本原理和实际应用(超详细)
c语言·网络·c++·笔记·qt·http·udp
四维碎片2 天前
【Qt】大数据量表格刷新优化--只刷新可见区域
开发语言·qt
一叶之秋14122 天前
Qt开发初识
开发语言·qt
梵尔纳多2 天前
ffmpeg 使用滤镜实现播放倍速
c++·qt·ffmpeg
QT 小鲜肉2 天前
【QT/C++】Qt网络编程进阶:TCP网络编程的基本原理和实际应用(超详细)
c语言·开发语言·网络·c++·qt·学习·tcp/ip
Tony小周3 天前
使用QKeyEvent keyPress(QEvent::KeyPress, key模拟键盘发送事件,会导致主程序卡死
嵌入式硬件·qt