Ted Middleton
Ted Middleton

Reputation: 7304

Interpreting QCloseEvent differently

I have a desktop windows application programmed in C++ with Qt. The application has several top - level windows which occasionally need to be closed and recreated programmatically. Also, when the user of the program clicks on the close button (the one next to the minimize and maximize buttons) the whole program is supposed to exit.

The problem I have is that in both cases the top level windows receive a closeEvent() call with a QCloseEvent object. I'd like to quit the program when I see that happen (because the user might have clicked the close button), but it's also possible that the window is closing because I'm deleting it programmatically to recreate it.

Is there a way of distinguishing between these two cases in QMainWindow::closeEvent()?

Upvotes: 2

Views: 347

Answers (2)

peppe
peppe

Reputation: 22826

Is there a way of distinguishing between these two cases in QMainWindow::closeEvent()?

Yes: the close event triggered by the user clicking on the window's close button will be a spontaneous event, the one triggered by you calling window->close() will not. See the documentation of QEvent::spontaneous() for more information.

Upvotes: 4

Pavel Strakhov
Pavel Strakhov

Reputation: 40522

When you need to close your window programmatically, use deleteLater() instead of close. The window will be closed and deleted. To reopen the window you will need to create another window object.

You can also use hide() method. The window will be hidden but not destroyed. It can be shown again using show().

In both described cases the close event does not happen and closeEvent() isn't called. So when closeEvent is called, you know that the user has pressed the close button.

Upvotes: 2

Related Questions