c++qtqmessagebox

Yes/No message box using QMessageBox


How do I show a message box with Yes/No buttons in Qt, and how do I check which of them was pressed?

I.e. a message box that looks like this:

enter image description here


Solution

  • You would use QMessageBox::question for that.

    Example in a hypothetical widget's slot:

    #include <QApplication>
    #include <QMessageBox>
    #include <QDebug>
    
    // ...
    
    void MyWidget::someSlot() {
      QMessageBox::StandardButton reply;
      reply = QMessageBox::question(this, "Test", "Quit?",
                                    QMessageBox::Yes|QMessageBox::No);
      if (reply == QMessageBox::Yes) {
        qDebug() << "Yes was clicked";
        QApplication::quit();
      } else {
        qDebug() << "Yes was *not* clicked";
      }
    }
    

    Should work on Qt 4 and 5, requires QT += widgets on Qt 5, and CONFIG += console on Win32 to see qDebug() output.

    See the StandardButton enum to get a list of buttons you can use; the function returns the button that was clicked. You can set a default button with an extra argument (Qt "chooses a suitable default automatically" if you don't or specify QMessageBox::NoButton).