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

相关推荐
秋田君19 小时前
QT_QT布局详解
开发语言·数据库·qt
辞旧 lekkk20 小时前
【Qt系统相关】鼠标事件
linux·开发语言·qt·学习·计算机外设·萌新
brave_zhao21 小时前
什么是Qt Designer
开发语言·qt
贺国亚1 天前
A2A协议与Agent互操作-Task生命周期
开发语言·qt
luoyayun3611 天前
Qt + FFmpeg 视频工具:视频一键压缩功能实现
qt·ffmpeg·音视频·视频压缩
blueman88881 天前
Qt5通过vcpkg中调用时,在debug模式下调试时总是调用release的plugins文件夹中的dll
c++·qt·cmake
南国韭菜2 天前
【无标题】
c++·qt
旋律翼22 天前
Qt Bridges for C# 深度技术解析
开发语言·qt·c#
郝学胜-神的一滴2 天前
Qt 高级编程 035:无边框窗口+自定义标题栏 完整实现详解
开发语言·c++·qt·程序人生·用户界面
辞旧 lekkk2 天前
CMake工程指南(一)
linux·运维·服务器·开发语言·qt·学习·萌新