Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to close Message Box Window



  • Hello Developers,

    I open Message Box window using following code and want to close it after user has pressed either yes or no button. Can you please inform me how can I do it.

    void MainWindow::on_pushButton_clicked()
    {
      
        QMessageBox::StandardButton reply = QMessageBox::question(this,
                                            "My Title", "This is my custom Message",
                                            QMessageBox::Yes | QMessageBox::No);
        if(reply == QMessageBox::Yes){
           // QApplication::quit();
            //QMessageBox::Close();
            qDebug() << "Yes is clicked";
        }
        else
        {
    
            qDebug() << "No is clicked";
        }
    

    Thanks a lot :)


  • Lifetime Qt Champion

    Hi,

    The QMessageBox will be automatically closed when clicking on either of these buttons. Isn't that the case for you ?



  • Hello @SGaist

    Thank you very much for your fast reply. I think it was closing but my main window was not refreshing fast due to which I could not see closing of Message Box.

    In other words, I could see closing of Message box only after I have put some milliseconds delay (generated using single shot timer) before checking value of variable "reply" as given below.

    void MainWindow::on_pushButton_clicked()
    {
      
        QMessageBox::StandardButton reply = QMessageBox::question(this,
                                            "My Title", "This is my custom Message",
                                            QMessageBox::Yes | QMessageBox::No);
      DelayMilliseconds(200); 
       if(reply == QMessageBox::Yes){
           // QApplication::quit();
            //QMessageBox::Close();
            qDebug() << "Yes is clicked";
        }
        else
        {
    
            qDebug() << "No is clicked";
        }
    

    Please explain me if I have made any mistake or not understanding it correctly.
    Thanks a lot :)


  • Lifetime Qt Champion

    What refreshing are you talking about ?



  • @SGaist

    I think he meant, that if he uncomment the "QApplication::quit", he does not see the result of the MSG-Box, because the main program gets killed instantly. So he cant check the result (output) of the if-clause.
    Which makes sence :)

    @saurabh162
    You dont need any delay.
    Just keep the code as it is. Just remove the "QApplication::quit" and the "QMessageBox::Close", as the MessageBox gets closed after ANY ButtonPress Event (YES, NO, CANCEL, SAVE...whatever...)
    Your MessageBox behaves like it should.


Log in to reply