Home > OS >  Yes/No message box using QMessageBox
Yes/No message box using QMessageBox

Time:12-31

I want to close the application when I click "Yes", but it closes even I press "No". What is wrong?

void secondwindow::on_pushButton_clicked()
{
    QMessageBox msg;
    msg.setWindowTitle("Quit");
    msg.setText("Are you sure you want to quit?");
    msg.setIcon(QMessageBox::Question);
    msg.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
    msg.setStyleSheet(QString::fromUtf8("background-color: white;"));
    if(msg.exec()==QMessageBox::Yes){
        QApplication::quit();
    }
}

CodePudding user response:

You can check msg.result() code:

// if(msg.exec()==QMessageBox::Yes){
//     QApplication::quit();
// }

msg.exec();
if (msg.result() == QMessageBox::Yes){
    QApplication::quit();
}

CodePudding user response:

Based on your code, it looks like you are closing the application if the user clicks the Yes button, but it is also closing when the user clicks the No button. This is happening because you are calling QApplication::quit() in both cases.

To fix this, you can simply add an else clause to your code to handle the case where the user clicks the No button:

if(msg.exec()==QMessageBox::Yes){
    QApplication::quit();
} else {
    // Do something else if the user clicks No
}
  •  Tags:  
  • c qt
  • Related