Important: Please read the Qt Code of Conduct -

Proper way to handling application quit/close with multiple windows

  • My application consists of one main/parent QMainWindow and then lots of QMainWindows that are spawned as children of the main QMainWindow.

    In the parent QMainWindow I've overriden the closeEvent() to prompt the user if they want to close the app.

    However, when quitting the app using CMD+Q or Quit from the menu, the other child QMainWindows will be randomly closed before the parent QMainWindow even gets the close event.

    I want to prompt the user before any of the QMainWindows get closed. What's the proper way to do this? Is overriding QApplication::event() and then prompting the user there the correct way, or am I overlooking something?

  • Lifetime Qt Champion

    @btse Why do you have more than one main window?

  • @jsulm Because we use them as a top level window. Our app consists of many top level windows, and having things like the built in toolbar and statusbar is useful.

  • the situation seems like the OP is relying too much opon event overrides and not using the signal/slot mechanism to handle the actions in the other windows.

    when CMD+Q is entered trigger a slot that exec() a "really quit?" dialog. If dialog return state is accepted then emit signal to all children windows telling them to close, and have parent window do nothing until it receive proper notification from all children windows that they have closed.

  • @Kent-Dorfman After digging into this more, things get a lot more tricky.

    I've tested adding my own QAction to the menuBar in order to override the default "Quit app" menu item/action which by default connects to the QCoreApplication::quit() slot. I connect this to my own slot where I prompt the user if they really want to quit. This works as expected when using Quit from the menu or "CMD+Q" shortcut.

    However, this does not account for the quitting from the dock. If I quit the app from the dock, then my "Do you want to quit?" dialog does not get shown at all.

    So it doesn't seem like there's a clean solution to handle a quit dialog for applications with multiple top level windows without adding some kind of native code.

  • In my apps, i'm using this code in a QApplication subclass:

    bool Application::event(QEvent *event)
    bool handled=false;
    case QEvent::Close:

    It handles the Dock as well on Mac.

  • @mpergand Thanks! This seems to be pretty close to what I want. Have you set setQuitOnLastWindowClosed(false) on your app also?

  • @btse said in Proper way to handling application quit/close with multiple windows:

    Have you set setQuitOnLastWindowClosed(false) on your app also?

    Only for MacOS:

    #if defined(Q_OS_MAC)

  • @mpergand Awesome! thank you very much

Log in to reply