Yes/No message box using QMessageBox

前端 未结 7 2101
渐次进展
渐次进展 2021-01-30 05:59

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:

7条回答
  •  滥情空心
    2021-01-30 06:44

    You would use QMessageBox::question for that.

    Example in a hypothetical widget's slot:

    #include 
    #include 
    #include 
    
    // ...
    
    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).

提交回复
热议问题