2

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();
}
Makketronix
  • 1,389
  • 1
  • 11
  • 31

1 Answers1

3

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.

demonplus
  • 5,613
  • 12
  • 49
  • 68
  • 1
    Ha! I created multiple engines but only the first one is used. I guess I can trace it through the source more, but that is just details. Interesting implementation technique... – Makketronix Oct 05 '16 at 14:13
  • @Makketronix Interesting, I guess you will be able to figure why only the first is used by looking into sources also – demonplus Oct 05 '16 at 14:16