1

I have 2 pages, a homepage, a settings page. I open the settings page on mainwindow. when the user wants to close the settings page. I want to ask the user if you are sure you want to log out. How can I ask such a question to just close the settings page without the app closing?

Mainwindow is my homepage

Lion King
  • 32,851
  • 25
  • 81
  • 143
ysncck
  • 117
  • 7
  • 1
    Does this answer your question? [Yes/No message box using QMessageBox](https://stackoverflow.com/questions/13111669/yes-no-message-box-using-qmessagebox) – Lion King Jul 19 '22 at 10:58
  • @LionKing What I'm looking for is that the messagebox pops up when I press the red exit button on the title bar. – ysncck Jul 19 '22 at 11:02
  • 3
    Put the code that shows the Yes/No Message box in the `closeEvent` method of the setting window. look at [this](https://stackoverflow.com/questions/17480984/qt-how-do-i-handle-the-event-of-the-user-pressing-the-x-close-button) question. – Lion King Jul 19 '22 at 11:11
  • Tahnk you for your comment ıt ıs helpful for me – ysncck Jul 19 '22 at 11:21

1 Answers1

1

This is what I do in my preference dialog:

PreferencesDialog::PreferencesDialog(QWidget *parent)
  : QDialog(parent, Qt::Tool)
{
  ...
  QDialogButtonBox* buttonBox = new QDialogButtonBox(this);
  buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults);
  buttonBox->setFocusPolicy(Qt::TabFocus);
  mainLayout->addWidget(buttonBox);
  setLayout(mainLayout);

  connect(buttonBox, &QDialogButtonBox::rejected, this, &PreferencesDialog::reject);
  connect(buttonBox, &QDialogButtonBox::accepted, this, &PreferencesDialog::accept);
  connect(buttonBox->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, this, &PreferencesDialog::revert);
  ...
}

You can then do something like this in the accept slot, although I think it is a bad idea. This would result in distractive user experience. The common behaviour that an average user expects is just the above. So, I would ignore the below code. But I will provide it for you for completeness:

QMessageBox messageBox;
messageBox.setWindowTitle("Close the preferences?");
messageBox.setIcon(QMessageBox::Warning);
messageBox.setText(...);
messageBox.setInformativeText(tr("Are you sure you want to close the preferences?"));
messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
messageBox.setDefaultButton(QMessageBox::No);

const int ret = messageBox.exec();
switch (ret) {
  case QMessageBox::Yes:
    ...
  case QMessageBox::No:
    ...
    break;
  default:
    break;
}
László Papp
  • 51,870
  • 39
  • 111
  • 135