Quit-application-action-with-do-no-show-again-option
Jump to navigation
Jump to search
Usually applications have a Quit action in the context menu,
The following code will show a question dialog to the user to make sure that (s)he really wants to quit.
There is also an option to supress this message.
<br />void MainWindow::on_actionQuit_triggered()<br />{<br /> bool exit = false;<br /> QSettings settings;<br /> settings.beginGroup("MainWindow&quot;);<br /> if (settings.value("quitWithoutPrompt&quot;).toBool()) {<br /> exit = true;<br /> } else {<br /> QMessageBox quitQuestion;<br /> QCheckBox checkBox;<br /> checkBox.setText(tr("Do not ask again&quot;));<br /> quitQuestion.setCheckBox(&checkBox);<br /> quitQuestion.setText(tr("Do you really want to exit this program?"));<br /> quitQuestion.setWindowTitle(tr("Are you sure?"));<br /> quitQuestion.setStandardButtons(QMessageBox::No | QMessageBox::Yes);<br /> quitQuestion.setDefaultButton(QMessageBox::No);<br /> quitQuestion.exec&amp;#40;&#41;;<br /> if (quitQuestion.result() == QMessageBox::Yes) {<br /> settings.setValue("quitWithoutPrompt&quot;, checkBox.isChecked());<br /> exit = true;<br /> }<br /> }<br /> settings.endGroup();<br /> if (exit)<br /> QCoreApplication::quit();<br />}<br />
To reenable this message you will need to clear the mainwindow/quitWithoutPrompt key trough the default QSettings. The following code can be used do do that:
void MainWindow::setQuitQuestinEnabled()
{
QSettings settings;
settings.beginGroup("MainWindow");
settings.setValue("quitWithoutPrompt", false);
settings.endGroup();
}