Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show a dialog before closing the program in Qt

Tags:

c++

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

like image 290
Ali Avatar asked Oct 29 '12 20:10

Ali


2 Answers

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.

like image 180
cppguy Avatar answered Oct 03 '22 11:10

cppguy


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

}
like image 39
NirZ Avatar answered Oct 03 '22 10:10

NirZ