qtqqmlapplicationengine

Qt: How does QGuiApplication and QQmlApplicationEngine interact?


I am trying to understand the underlying magic behind Qt. It seems that I am missing an important concept in how QML and C++ interact.

In the following "Hello World" demo, the most basic, an app is declared, an engine is declared, then an app is executed.

Nowhere at this level we are telling the app to use the engine. How does qt know?

int main(int argc, char *argv[])
{
  QGuiApplication app(argc, argv);

  QQmlApplicationEngine engine;
  engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

  return app.exec();
}

Solution

  • There is no magic, it actually happens. In Qt sources there is the following in QQmlApplicationEnginePrivate.cpp:

    QCoreApplication::instance()->setProperty(
     "__qml_using_qqmlapplicationengine", QVariant(true));
    

    This is also answers the question how they know that engine should use the app.

    QQmlApplicationEngine just takes single instance() of QCoreApplication or its descendant QGuiApplication and uses it.