1

Please tell me where I made a mistake? My code:

void deletetable::on_pb_dell_clicked()
{
    QMessageBox messageBox(QMessageBox::Question,
            tr("Sure want to quit?"), tr("Sure to quit?"), QMessageBox::Yes | QMessageBox::No, this);
    messageBox.setButtonText(QMessageBox::Yes, tr("Yes"));
    messageBox.setButtonText(QMessageBox::No, tr("No"));
    messageBox.exec();
    if (messageBox.QMessageBox::Yes) {
        emit deleteYear(year);
        close();
    } else {
        
    }
}

my function deleteYear(year) works in any condition, i.e. if I click "No", the function will still work. I took an example from here https://stackoverflow.com/a/31533126/13023647

Alex Rebell
  • 465
  • 3
  • 15

1 Answers1

3
messageBox.QMessageBox::Yes

Is just accessing the enum Yes, which is going to evaluate the same each time.

You want to capture the actual response from the question and query that, such as:

auto response = QMessageBox::question(this, "Save", "Do you wish to save?", QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);


if (response == QMessageBox::Save) { ... }

See https://doc.qt.io/qt-5/qmessagebox.html#question here for more info.


To keep the same format above you can get the response with messageBox.result() e.g.

if (messageBox.result() == QMessageBox::Yes) { ... }
0RR
  • 1,538
  • 10
  • 21
  • 1
    Great example, thank you. But the fact is that I need to translate the standard "Yes" and "No" buttons into another language, so I use the above construction. – Alex Rebell Jan 25 '21 at 09:15
  • 1
    @AlexRebell You can take the return value from the `exec()` call and query that e.g. `auto response = messageBox.exec();` and `if (response == QMessageBox::Yes) {...}` – 0RR Jan 25 '21 at 09:25
  • 2
    Super! What you need, thank you very much! Update your answer,I'll mark it solved. – Alex Rebell Jan 25 '21 at 09:51
  • Note that apparently Qt 6.2 has marked `QMessageBox::question` obsolete. – Gwyneth Llewelyn Aug 18 '22 at 12:53