Important: Please read the Qt Code of Conduct -

Exit of application from GUI (QMessageBox) not working

  • Hi,

    I would like to have a message box at the program start with a "yes" and a "no" button.
    If "no" is pressed the software should quit.

    I tried this in the following way:

    void MainWindow::discalimer()
        QMessageBox msgBox(
                    QMessageBox::Yes | QMessageBox::No);
        msgBox.setButtonText(QMessageBox::Yes, trUtf8("Yes!"));
        msgBox.setButtonText(QMessageBox::No, trUtf8("No!"));
        connect( msgBox.button(QMessageBox::No), SIGNAL(clicked()) ,qApp, SLOT(quit()) );

    This function I call in the constructor of my MainWindow after ui->setupUi(this);

    I also tried to call the function somewhere else but my software always starts.
    Why is that and how can I solve it?

    Sadly I could not find a solution with google :-/

    Thank you very much :-)

  • One way of doing this is to call your MainWindow::close() and then connect the QApplication::lastWindowClosed() signal to QApplication::quit().

  • Hi,
    Calling a .exec in the constructor of your MainWindow won't work! The event handler of the QApplication is not active at that time.
    First create your MainWindow, then start your QApplication (in your main() function).
    But then your MainWindow will be visible if you do not set it hidden. Create a messageBox in a single shot timer and you should be good.
    Maybe an other way is to use a SplashScreen. No idea if you are able to use button in that one.
    Nup, no buttons, but you could use the buttonpressed, so set a timer with e.g. 5 seconds. If you do not click the splashscreen, start the program. IF you do click it, stop it?
    But the first option is better IYAM.

  • Lifetime Qt Champion


    To add to @Jeroentjehome, if you need to quit the application before the MainWindow is constructed then why not use that QMessageBox in main before constructing your MainWindow ?

  • Thank you all very much.

    I now created a QMessageBox in the main.cpp before constructing the MainWindow as SGaist suggested.
    If "no" is pressed calling QApplication::quit() does nothing, but just return 0 works perfectly fine :-)

Log in to reply