Search code examples
c++qtwindowdesktop

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


I want to show confirmation messagebox and block the screen before user leaves (alt + tab (close or loose focus)) MainWindow. How to do this?

here is my code

#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;
}

Solution

  • For close event:

    Reimplement closeEvent method in your MainWindow class. Link

    For window activation and deactivation events try following:

    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) ;
    }