Home > Software design >  QT C Ask to user before close window
QT C Ask to user before close window

Time:07-21

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

CodePudding user response:

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;
}
  •  Tags:  
  • c qt
  • Related