如何在离开(关闭或失去焦点)窗口之前显示模态确认消息

How to show a modal confirmation message before leaving (closing or losing focus) of a window?

本文关键字:窗口 显示 消息 确认 模态 焦点 失去 离开      更新时间:2023-10-16

我想在用户离开(alt + tab(关闭或松散焦点))主窗口之前显示确认消息框并阻止屏幕。如何做到这一点?

这是我的代码

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QMainWindow::showFullScreen();
    this->installEventFilter(this);
}
MainWindow::~MainWindow()
{
    delete ui;
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event){
    if(event->type() == 128){
        QMessageBox::information(this, "title", "text", QMessageBox::Ok | QMessageBox::Cancel);
        return true;
    }
    return true;
}

对于关闭事件:

在MainWindow类中重新实现closeEvent方法。链接

对于窗口激活和取消激活事件,请尝试以下操作:

bool MainWindow::event(QEvent * e) // overloading event(QEvent*) method of QMainWindow 
{
    switch(e->type())
    {
        // ...
        case QEvent::WindowActivate :
            // gained focus
            break ;
        case QEvent::WindowDeactivate :
            // lost focus
            break ;
        // ...
    } ;
    return QMainWindow::event(e) ;
}