Yes/No message box using QMessageBox

前端 未结 7 2099
渐次进展
渐次进展 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:30

    QMessageBox includes static methods to quickly ask such questions:

    #include 
    #include 
    
    int main(int argc, char **argv)
    {
        QApplication app{argc, argv};
        while (QMessageBox::question(nullptr,
                                     qApp->translate("my_app", "Test"),
                                     qApp->translate("my_app", "Are you sure you want to quit?"),
                                     QMessageBox::Yes|QMessageBox::No)
               != QMessageBox::Yes)
            // ask again
            ;
    }
    

    If your needs are more complex than provided for by the static methods, you should construct a new QMessageBox object, and call its exec() method to show it in its own event loop and obtain the pressed button identifier. For example, we might want to make "No" be the default answer:

    #include 
    #include 
    
    int main(int argc, char **argv)
    {
        QApplication app{argc, argv};
        auto question = new QMessageBox(QMessageBox::Question,
                                        qApp->translate("my_app", "Test"),
                                        qApp->translate("my_app", "Are you sure you want to quit?"),
                                        QMessageBox::Yes|QMessageBox::No,
                                        nullptr);
        question->setDefaultButton(QMessageBox::No);
    
        while (question->exec() != QMessageBox::Yes)
            // ask again
            ;
    }
    

提交回复
热议问题