How to do cleaning up on exit in Qt

前端 未结 2 1985
情深已故
情深已故 2021-02-02 10:17

I\'d like to do some house keeping stuff (like writing to a file etc) in a Qt app before the app exits. How can I get to this function (exit or whatever is called) in Qt?

相关标签:
2条回答
  • 2021-02-02 10:58

    In regards to Silas Parker's answer, the Qt documentation says this about the aboutToQuit signal:

    The signal is particularly useful if your application has to do some last-second cleanup. Note that no user interaction is possible in this state.

    If you want your application to be able to cancel the exiting process or allow the user to perform a last minute change before the application closes, then you can do this by handling the closeEvent function in your MainWindow.

    void MainWindow::closeEvent(QCloseEvent *event)
    {
        if (maybeSave()) {
            writeSettings();
            event->accept();
        } else {
            event->ignore();
        }
    }
    

    See the closeEvent documentation for more information.

    0 讨论(0)
  • 2021-02-02 11:01

    You need to connect a slot with the clean up code to the QCoreApplication::aboutToQuit() signal.

    This allows you to delete QObjects with QObject::deleteLater() and the objects will be deleted as you have not yet left the main application event loop.

    If you are using a C library that requires a 'shutdown' call you can normally do that after the return from QCoreApplication::exec().

    Example for both techniques:

    int main(int,char**)
    {
      QApplication app;
      library_init();
      QWidget window;
      window.show();
      QObject::connect(&app, SIGNAL(aboutToQuit()), &window, SLOT(closing()));
      const int retval = app.exec();
      library_close();
      return retval;
    }
    
    0 讨论(0)
提交回复
热议问题