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:
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
).
I have a question concerning the way you dynamically generate the message box: is it better to do it like this or predefine the whole thing (create and store the message box in a variable etc.) and then simply call it when needed?
@rbaleksandar It's better to use the QMessageBox static methods. Qt will clean up any memory used when the methods return, there is no need to keep one in memory permanently.
Thanks, it makes sense. After all this part of the UI is not something that 1)requires a lot of resources thus takes some time to load and 2)is often or even constantly on the screen for the user to see it.
Best answer ever.