mosg
mosg

Reputation: 12391

HowTo correctly close QDialog when main windows is hidden?

I have some kind of dilemma.

I'm using:

I wrote small Qt application, base on QMainWindow class, where also exists settings dialog (QDialog). Every works fine in GUI mode. After that I started to change my project to make it visible only in tray. Just comment in main.cpp show() method, like this:

MainWindow w;
//w.show();

return app.exec();

But from tray, I need to launch settings dialog, which is implemented in mainwindow.h/.cpp files. I added to tray menu action (QAction) which is starts that settings dialog. And here comes the unexpected problem: when I tried to close this settings dialog with [ X ] close button (in top right corner) my app closed!

Here is the action slot:

void MainWindow::onOpenSettingsDlgClicked()
{
     SettingsDlg dlg( this );
     dlg.exec();
}

I have tried to reimplement virtual reject() method for the settings dialog class, and set there only hide() function, but that solution not helped.

What I'm doing wrong?

Thanks you!

Upvotes: 3

Views: 1396

Answers (2)

Jake W
Jake W

Reputation: 2858

Just found another option which seems better is to override closeEvent of the QDialog to only hide it.

void PrefDialog::closeEvent(QCloseEvent *event) {
    this->hide();
    event->ignore();
}

I found this seems better because it doesn't change the global application behaviour.

Upvotes: 0

azf
azf

Reputation: 2189

You should turn off the quitOnLastWindowClosed property which is turned on by default as defined in the doc (http://doc.qt.nokia.com/latest/qapplication.html#quitOnLastWindowClosed-prop)

This said, you'll have to handle the termination of your QApplication yourself, maybe with an [quit] entry in the tray menu.

Upvotes: 5

Related Questions