Qt/C++ – How to differentiate between closing main window from an external app and clicking close button click from title bar?

98 views Asked by At

I currently have a QMessageBox appear on exiting from MainWindow, asksing "Are you sure?". While updating the app through InnoSetup installer file, the installer tries to close the MainWindow, however, the "Are you sure?" button still appears, which I don't want.

I tried to check for event->spontaneous() inside closeEvent(QCloseEvent *event) but it returns true in both the cases.

How to make "Are you sure?" appear only when the user presses the close button?

I am using Windows 10.

2

There are 2 answers

0
Bharath Ram On BEST ANSWER

Thanks to mugiseyebrows's answer, I solved the problem like so. Instead of a file, I set a registry key.

Following code goes at the end of InnoSetup ISS file:

[Code]
function InitializeSetup(): Boolean;
begin
  RegWriteStringValue(HKEY_CURRENT_USER, 'SOFTWARE\SoftwareName\Settings', 'warn_on_exit', 'false');
  Result := True;
end;

procedure DeinitializeSetup();
begin
  RegWriteStringValue(HKEY_CURRENT_USER, 'SOFTWARE\SoftwareName\Settings', 'warn_on_exit', 'true');  
end;

Following is the closeEvent() code in Qt:

QSettings settings("HKEY_CURRENT_USER\\SOFTWARE\\SoftwareName\\Settings", QSettings::Registry32Format);

void MainWindow::closeEvent(QCloseEvent *ev){
    if(settings.value("warn_on_exit",true).toBool())){
        QMessageBox qmb(this);
        qmb.setIcon(QMessageBox::Question);
        qmb.setWindowTitle("");
        qmb.setText("Are you sure you want to exit?");
        qmb.addButton("Yes",QMessageBox::YesRole);
        qmb.addButton("No",QMessageBox::NoRole);
        qmb.exec();
        if(qmb.clickedButton()->text()=="No"){
            ev->ignore();
            return;
        }
        QMainWindow::closeEvent(ev);
    }
0
mugiseyebrows On

I don't think it's possible, installer is probably sends WM_CLOSE message, just like close button do.

As a workaround you can use PrepareToInstall InnoSetup section to place temporary file into known location, and check for presence of this file in closeEvent. Don't forget to remove this file on next run or after install.