Search code examples
c++qtclose-button

How do I handle the event of the user pressing the 'X' (close) button?


In Qt, what is the slot that corresponds to the event of the user clicking the 'X' (close) button of the window frame, i.e., this button:

Close button of the window

If there isn't a slot for this, is there any other way to trigger a function after the user presses the close button?


Solution

  • If you have a QMainWindow you can override closeEvent method.

    #include <QCloseEvent>
    void MainWindow::closeEvent (QCloseEvent *event)
    {
        QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,
                                                                    tr("Are you sure?\n"),
                                                                    QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                                                    QMessageBox::Yes);
        if (resBtn != QMessageBox::Yes) {
            event->ignore();
        } else {
            event->accept();
        }
    }
    


    If you're subclassing a QDialog, the closeEvent will not be called and so you have to override reject():

    void MyDialog::reject()
    {
        QMessageBox::StandardButton resBtn = QMessageBox::Yes;
        if (changes) {
            resBtn = QMessageBox::question( this, APP_NAME,
                                            tr("Are you sure?\n"),
                                            QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                            QMessageBox::Yes);
        }
        if (resBtn == QMessageBox::Yes) {
            QDialog::reject();
        }
    }