Warm tip: This article is reproduced from serverfault.com, please click

Yes/No message box using QMessageBox

发布于 2012-10-28 18:24:20

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

Questioner
sashoalm
Viewed
0
Mat 2013-08-07 19:44:57

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).