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

相关推荐
我是菜鸟0713号1 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_1 天前
QT(4)
开发语言·汇编·c++·qt·算法
lqjun08272 天前
Qt程序单独运行报错问题
开发语言·qt
酷飞飞2 天前
Qt Designer与事件处理
开发语言·qt·命令模式
mkhase2 天前
9.12-QT-基本登陆界面实现
java·jvm·qt
咕噜咕噜啦啦2 天前
Qt之快捷键、事件处理、自定义按键——完成记事本项目
开发语言·qt
Quz2 天前
QML Charts组件之折线图的鼠标交互
qt
眠りたいです2 天前
基于脚手架微服务的视频点播系统-数据管理与网络通信部分的预备工作
c++·qt·ui·微服务·云原生·架构·媒体
bikong72 天前
Qt/C++,windows多进程demo
c++·windows·qt
油炸自行车2 天前
【Qt】Window环境下搭建Qt6、MSVC2022开发环境(无需提前安装Visual Studio)
qt·visual studio·qt6·msvc2022·qt creator 17.0