I don't know if this is a good example, but I used to create my own subclass of the GuiApplication class from QGuiApplication
#ifndef GUIAPPLICATION_H #define GUIAPPLICATION_H #include <QGuiApplication> class GuiApplication : public QGuiApplication { Q_OBJECT public: #ifdef Q_QDOC explicit GuiApplication(int &argc, char **argv); #else explicit GuiApplication(int &argc, char **argv, int = ApplicationFlags); #endif bool notify(QObject *receiver, QEvent *event); signals: void back(); }; #endif // GUIAPPLICATION_H
This is for cpp codes
#include "guiapplication.h" #include <QDebug> GuiApplication::GuiApplication(int &argc, char **argv, int) : QGuiApplication(argc, argv) { } bool GuiApplication::notify(QObject *receiver, QEvent *event) { // to intercept android back button #ifdef Q_OS_ANDROID if(event->type() == QEvent::Close) { emit back(); return false; } else { return QGuiApplication::notify(receiver,event); } #else return QGuiApplication::notify(receiver,event); #endif }
For main.cpp
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "guiapplication.h" int main(int argc, char *argv[]) { // QGuiApplication app(argc, argv); GuiApplication app(argc, argv); QQmlApplicationEngine engine; QQmlContext *rootContext = engine.rootContext(); rootContext->setContextProperty("GUI", &app); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
and finally for main.qml
import QtQuick 2.3 import QtQuick.Controls 1.2 ApplicationWindow { id: applicationWindow visible: true width: 360 height: 360 Connections { target: GUI onBack: console.log("back") } }
source share