JimmyG
JimmyG

Reputation: 131

QMessageBox exec doesnt seem to return QDialog::DialogCode

My application's closeEvent() looks nearly like this (Qt 5.8.0 on Windows):

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(some_changes_were_made)  // bool
    {
        QMessageBox mbox;
        mbox.setText("Page(s) have been changed.");
        mbox.setInformativeText("What do you want to do?");
        mbox.addButton("Exit now", QMessageBox::AcceptRole);
        mbox.addButton("Save page(s) first", QMessageBox::RejectRole);

        int exit_code = mbox.exec();

        if(exit_code == QDialog::Rejected)
        {
           // bail out of the close event so the user can save pages
           event->ignore();
           return;
        }
    }

    event->accept();
}

I'm curious if the documentation is wrong, which states that exec() returns a QDialog::DialogCode. It actually seems to return the QMessageBox::ButtonRole (which interestingly is the inverse value). Or am I just doing something totally wrong here?

Please forgive any typos, as I'm unable to copy the actual code here.

Upvotes: 1

Views: 488

Answers (1)

NP Rooski  Z
NP Rooski Z

Reputation: 3677

Check QMessageBox reference here.

It is supposed to return one of the standardButton replies. You are using QDialogBox replies, QMessageBox has already overriden QDialogBox's exec method.

You want to check something like this:

switch (exit_code) {
  case QMessageBox::Save:
      // Save was clicked
      break;
  case QMessageBox::Discard:
      // Don't Save was clicked
      break;
  case QMessageBox::Cancel:
      // Cancel was clicked
      break;
  default:
      // should never be reached
      break;
}

Source from the same link.

Upvotes: 1

Related Questions