qtmobileqmlforceclose

QT or QML: Catching app close event in mobile app


I have an app which uses a QML MediaPlayer to play music. Via:

   Connections {
      target: Qt.application
      onStateChanged: {
         // ...
      }
   }

I am able to note when the app goes to the background, or when it comes to the foreground again.

However, I don't get any event when the user closes the app. The problem is, when playing music, and the app is closed, the music playback continues. As a result, I need a way to catch the close event and stop music playback.

I am on Ubuntu Touch, and therefore I have no Window instance where I could catch the closing event. In the QGuiApplication / Qt.application there seems to be no viable signal either; I have tried catching lastWindowClosed, but it never gets triggered.

Long story short: How can I get notified when the app is about to close so I can stop music playback?

My main.cpp is pretty much the default and looks like:

int main(int argc, char *argv[])
{
    QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication* app = new QGuiApplication(argc, (char**)argv);

    QQuickView *view = new QQuickView();
    view->setSource(QUrl("qrc:/Main.qml"));
    view->setResizeMode(QQuickView::SizeRootObjectToView);
    view->show();

    return app->exec();
}

Solution

  • Got it, after googling even more. Some guy at the QT forum revealed:

       Connections {
          target: Qt.application
    
          onAboutToQuit: {
             audioPlayer.stop()
          }
    

    This works