Ali
Ali

Reputation: 171

show a dialog before closing the program in Qt

I want to show the dialog before closing the program in Qt whether the user wants to cancel or save the program, i.e. by clicking on cancel the user has chance to return to program with uncleaned state, like windows paint, or notepad in which the aware dialog before closing appear alerting the users? by the way I use Qt

Upvotes: 12

Views: 9137

Answers (2)

NirZ
NirZ

Reputation: 105

you can use the solution described here: https://web.archive.org/web/20170716164107/http://www.codeprogress.com/cpp/libraries/qt/HandlingQCloseEvent.php

you can simply override closeEvent function by:

#include <QCloseEvent>
#include <QMessageBox>
void MainWindow::closeEvent(QCloseEvent *event)  // show prompt when user wants to close app
{
    event->ignore();
    if (QMessageBox::Yes == QMessageBox::question(this, "Close Confirmation", "Exit?", QMessageBox::Yes | QMessageBox::No))
    {
        event->accept();
    }

}

Upvotes: 7

cppguy
cppguy

Reputation: 3713

If your application uses QMainWindow, overload the closeEvent() to show the dialog and only call QMainWindow::closeEvent if the user clicked ok in your dialog.

If your application uses a QDialog, overload the accept() slot and only call QDialog::accept if the user clicked ok in your dialog.

Upvotes: 19

Related Questions