QQmlApplicationEngine, qt_add_qml_module & Ahead-of-Time qmlsc Compilation

Cold-booting an embedded HMI from loose .qml files on eMMC or QSPI flash stalls first-frame scanout behind VFS block reads, recursive-descent parsing, and runtime QV4 bytecode or JIT page generation on a single-core Cortex-A7.

25 minfree previewLinux 6.12→ module 1 lab
What you'll learn
  • Configure qt_add_qml_module CMake targets so QML documents compile into canonical qrc:/qt/qml/ resources with complete .qmltypes metadata.
  • Analyze cold-boot latency across loose flash .qml parsing, qmlcachegen bytecode caching, and qmlsc ahead-of-time C++ binding compilation on Cortex-A7.
  • Verify URI-to-resource path resolution and static-vs-fallback binding startup budgets in ISO C++20.

Cold-Boot QML Parsing Costs and Why Cortex-A7 Needs Ahead-of-Time Compilation

When an embedded appliance launches QQmlApplicationEngine against raw .qml files stored on an eMMC or QSPI root filesystem, first-frame latency suffers three sequential penalties before a single pixel reaches the display panel. First, the Linux kernel VFS issues dozens of scattered small-file reads for .qml documents and qmldir manifests. Second, the QML frontend tokenizes UTF-8 text and allocates abstract syntax trees in heap RAM. Third, the QV4 JavaScript engine generates bytecode and, on supported targets, allocates executable JIT pages just to evaluate simple arithmetic bindings.

On a 528 MHz..792 MHz single-core ARMv7-A Cortex-A7 (i.MX6ULL) or a fast-boot automotive cluster required to show telltales under 500 ms, burning hundreds of milliseconds parsing text that never changes in the field is pure waste. Qt 6.8 eliminates those runtime stages with qt_add_qml_module: CMake synthesizes qmldir, runs qmltyperegistrar to emit .qmltypes schemas, embeds everything under qrc:/qt/qml/, and invokes qmlcachegen or qmlsc ahead of time to compile typed bindings straight into linked C++.

fig_m01_l01_a.svg — Build-time qmlsc C++ binding compilation versus…

Figure 1.1a. Build-time C++ binding compilation versus cold-boot VFS flash parsing and V4 JIT.

mental model: Shipping raw .qml source text into production firmware is like deploying uncompiled C++ source files onto an industrial controller and running a parser on every power-on instead of linking precompiled machine code directly into the read-only ELF image.

Where it stops working: Ahead-of-time qmlsc compilation translates statically typed bindings into C++ functions, whereas untyped var properties, eval() calls, or dynamic context lookups still fall back to the QV4 runtime interpreter.

definition (Ahead-of-Time QML Script Compiler (qmlsc)): Introduced in the Qt 6 QML compilation pipeline alongside qt_add_qml_module and qmltyperegistrar, qmlsc compiles statically typed QML binding expressions and JavaScript functions directly into native C++ translation units linked into the binary under canonical qrc:/qt/qml/ resource paths.

ast_m01_l01.svg — qt_add_qml_module + .qmltypes + qmlsc turns typed QML…step 1/4
  1. Step 1. Run moc and qmltyperegistrar during the CMake build to emit complete .qmltypes metadata for the module.
  2. Step 2. Map dotted module URI Hmi.Shell into canonical qrc:/qt/qml/Hmi/Shell/ alongside its generated qmldir.
  3. Step 3. Compile typed QML expressions ahead of time into native C++ translation units with qmlsc.
  4. Step 4. Load the root component from qrc:/qt/qml/Hmi/Shell/qmldir with zero disk parsing or V4 JIT stalls.

Figure 1.1b. qt_add_qml_module + .qmltypes + qmlsc turns typed QML bindings into linked C++ under qrc:/qt/qml/.

Canonical Resource Prefixes, Type Registration, and Backing Targets in CMake

Under Qt 6 policy QTP0001 (enabled automatically by qt_standard_project_setup(REQUIRES 6.8)), every QML module URI maps deterministically onto qrc:/qt/qml/<URI-with-slashes>/. Declaring URI Hmi.Shell places qmldir and compiled units at qrc:/qt/qml/Hmi/Shell/, allowing engine.loadFromModule("Hmi.Shell", "Main") to resolve the root component without brittle hard-coded qrc:/ URLs or addImportPath() directory scans.

Inspect the CMake configuration below. Making the executable hmi_shell serve directly as the backing target of qt_add_qml_module guarantees that the static linker retains every generated type-registration symbol without separate plugin dlopen() overhead. Remember the strict static contract: qmlsc can emit direct C++ binding functions only when every referenced property carries an explicit static type inside .qmltypes rather than hiding behind untyped property var.

fig_m01_l01_b.svg — Generated qrc:/qt/qml/ module artifacts and host…

Figure 1.1b. Generated qrc:/qt/qml/ module artifacts and host startup budget verification pipeline.

Execution ModeBuild ArtifactCortex-A7 Cold-Boot WorkBinding Dispatch Mechanism
Loose .qml on flashRaw UTF-8 .qml textVFS open/read + lexer + AST + QV4 codegenQV4 interpreter or runtime JIT (PROT_EXEC pages)
qmlcachegen (Qt Quick)Embedded .qmlc bytecode + C++ loaderZero text parse; mmap-free .rodata table setupPrecompiled QV4 bytecode + C++ fast paths
qmlsc (STATIC / direct)Native *_qml.cpp C++ functionsDirect function-pointer registration in .textNative C++ getter/setter calls (0 QV4 boxing)
Untyped var / eval()Fallback bytecode thunkForces runtime scope search per evaluationDynamic QVariant / meta-object string lookup
learner@ksa: ~/gl-q03/m01-l01
learner@ksa:~/gl-q03/m01-l01$ bat -H 8 -H 14 CMakeLists.txt File: CMakeLists.txt    cmake_minimum_required(VERSION 3.28)    project(hmi_shell VERSION 1.0.0 LANGUAGES CXX)        set(CMAKE_CXX_STANDARD 20)    set(CMAKE_CXX_STANDARD_REQUIRED ON)        find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Qml Quick)  qt_standard_project_setup(REQUIRES 6.8)        qt_add_executable(hmi_shell        src/main.cpp    )      qt_add_qml_module(hmi_shell        URI Hmi.Shell        VERSION 1.0        QML_FILES            qml/Main.qml            qml/StatusHeader.qml            qml/FaultBanner.qml    )        target_link_libraries(hmi_shell PRIVATE        Qt6::Core        Qt6::Gui        Qt6::Qml        Qt6::Quick    )
  1. qt_standard_project_setup(REQUIRES 6.8) enables QTP0001 so URI Hmi.Shell embeds at qrc:/qt/qml/Hmi/Shell/.
  2. Attaching qt_add_qml_module directly to executable target hmi_shell links all AOT registration symbols statically.
qt_add_qml_module / qmlsc(3qt-ksa) at a glance — GL-Q03
qt_add_qml_module / qmlsc(3qt-ksa) GL-Q03 Quick Reference qt_add_qml_module / qmlsc(3qt-ksa) NAME       qt_add_qml_module, loadFromModule, qmlsc -- Qt 6.8 AOT QML module       packaging & C++ codegen SYNOPSIS       qt_standard_project_setup(REQUIRES 6.8) qt_add_qml_module(<target> URI       <Dotted.Uri> VERSION 1.0 QML_FILES ...)        // C++20 startup in src/main.cpp:       QQmlApplicationEngine engine;       engine.loadFromModule("Hmi.Shell", "Main");        CANONICAL RESOURCE RESOLUTION URI "Hmi.Shell" ->       qrc:/qt/qml/Hmi/Shell/qmldir Type metadata -> build/<target>.qmltypes       (emitted by moc + qmltyperegistrar) Static linter -> qmllint -U -Werror       flags unqualified or untyped bindings at build time Kernel Systems Academy      Lesson 1.1      qt_add_qml_module / qmlsc(3qt-ksa) GL-Q03 quick reference · full manual page: man 3qt-ksa qt_add_qml_module / qmlsc 

Modeling Canonical URI Resolution and AOT Cold-Start Latency in ISO C++20

Before cross-compiling a full Qt6::Quick rootfs image, we can verify module URI syntax rules, canonical qrc:/qt/qml/ path synthesis, and static-versus-fallback binding costs deterministically on the Linux host. In verify.cpp below, valid_uri() enforces Qt's dotted identifier grammar (rejecting leading, trailing, or consecutive dots), and uri_to_qrc_prefix() produces the exact QTP0001 resource prefix.

Next, analyze_module() contrasts three startup regimes across 60 bindings in Main.qml, StatusHeader.qml, and FaultBanner.qml: cold flash VFS reads plus AST/V4 JIT generation, qmlcachegen precompiled bytecode, and qmlsc direct C++ binding calls. Keep the host-target boundary clear: host C++20 proves URI mapping and static compilation coverage (fallback_bindings == 0), whereas real eMMC read latency and Cortex-A7 cache-miss timings must be measured on hardware with QML_IMPORT_TRACE=1.

learner@ksa: ~/gl-q03/m01-l01
learner@ksa:~/gl-q03/m01-l01$ bat -H 37 -H 51 verify.cpp File: verify.cpp    #include <cassert>    #include <cstdint>    #include <cstdio>    #include <string>    #include <string_view>    #include <vector>        struct QmlUnitSpec {      std::string_view type_name;      std::string_view rel_file;      uint32_t source_bytes;      uint32_t binding_count;      bool statically_typed;    };        struct StartupReport {      std::string canonical_qrc_prefix;      uint32_t flash_v4_jit_us = 0;      uint32_t bytecode_cache_us = 0;      uint32_t aot_qmlsc_us = 0;      uint32_t direct_cpp_bindings = 0;      uint32_t fallback_bindings = 0;    };        static bool valid_uri(std::string_view uri) {      if (uri.empty() || uri.front() == '.' || uri.back() == '.') return false;      for (size_t i = 0; i < uri.size(); ++i) {        char c = uri[i];        if (c == '.' && uri[i + 1] == '.') return false;        bool ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||                  (c >= '0' && c <= '9') || c == '_' || c == '.';        if (!ok) return false;      }      return true;    }      static std::string uri_to_qrc_prefix(std::string_view uri) {      assert(valid_uri(uri));      std::string out = "qrc:/qt/qml/";      for (char c : uri) out.push_back(c == '.' ? '/' : c);      out.push_back('/');      return out;    }        static StartupReport analyze_module(std::string_view uri,                                        const std::vector<QmlUnitSpec>& units) {      StartupReport rep{uri_to_qrc_prefix(uri)};      for (const auto& u : units) {        rep.flash_v4_jit_us += 900U + (u.source_bytes / 4U) + u.binding_count * 85U;        rep.bytecode_cache_us += 95U + u.binding_count * 22U;      rep.aot_qmlsc_us += 65U;        if (u.statically_typed) {          rep.aot_qmlsc_us += u.binding_count * 6U;          rep.direct_cpp_bindings += u.binding_count;        } else {          rep.aot_qmlsc_us += u.binding_count * 42U;          rep.fallback_bindings += u.binding_count;        }      }      return rep;    }        int main() {      assert(!valid_uri("") && !valid_uri(".Hmi.Shell") && !valid_uri("Hmi..Shell"));      assert(valid_uri("Hmi.Shell"));          const std::vector<QmlUnitSpec> shell_units = {          {"Main", "qml/Main.qml", 6400, 28, true},          {"StatusHeader", "qml/StatusHeader.qml", 4200, 18, true},          {"FaultBanner", "qml/FaultBanner.qml", 3800, 14, true},      };          StartupReport clean = analyze_module("Hmi.Shell", shell_units);      assert(clean.canonical_qrc_prefix == "qrc:/qt/qml/Hmi/Shell/");      assert(clean.direct_cpp_bindings == 60 && clean.fallback_bindings == 0);      assert(clean.aot_qmlsc_us < clean.bytecode_cache_us);      assert(clean.bytecode_cache_us < clean.flash_v4_jit_us);          std::vector<QmlUnitSpec> untyped = shell_units;      untyped[0].statically_typed = false;      StartupReport degraded = analyze_module("Hmi.Shell", untyped);      assert(degraded.fallback_bindings == 28 && degraded.aot_qmlsc_us > clean.aot_qmlsc_us);          std::printf("prefix=%s entry=%sqml/Main.qml\n",                  clean.canonical_qrc_prefix.c_str(),                  clean.canonical_qrc_prefix.c_str());      std::printf("flash_jit_us=%u cachegen_us=%u qmlsc_us=%u direct=%u fallback=%u\n",                  clean.flash_v4_jit_us, clean.bytecode_cache_us, clean.aot_qmlsc_us,                  clean.direct_cpp_bindings, clean.fallback_bindings);      return 0;    }
  1. uri_to_qrc_prefix converts dotted URI tokens directly into canonical qrc:/qt/qml/<Module/Path>/.
  2. Statically typed bindings compile into native C++ calls, whereas untyped QML units fall back to QV4.

Verifying Resource Path Mapping and Static Binding Compilation Counts

Inspect the shell execution transcript and strace trace below. uri_to_qrc_prefix("Hmi.Shell") maps cleanly to qrc:/qt/qml/Hmi/Shell/, while all 60 statically typed bindings across Main, StatusHeader, and FaultBanner compile with fallback = 0, shrinking modeled initialization cost from 11,400 us (loose flash + V4 JIT) to 1,605 us (qmlcachegen) and 555 us (qmlsc).

Notice in degraded what happens as soon as Main.qml loses static type annotations on its 28 bindings: fallback_bindings jumps to 28 and startup work nearly triples. Running qmllint with compiler warnings enabled (-Wqml) in CI catches every fallback before firmware reaches QA.

learner@ksa: ~/gl-q03/m01-l01
learner@ksa:~/gl-q03/m01-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q03/m01-l01./verifyprefix=qrc:/qt/qml/Hmi/Shell/ entry=qrc:/qt/qml/Hmi/Shell/qml/Main.qmlflash_jit_us=11400 cachegen_us=1605 qmlsc_us=555 direct=60 fallback=0learner@ksa:~/gl-q03/m01-l01
strace — learner@ksa: ~/gl-q03/m01-l01
learner@ksa:~/gl-q03/m01-l01strace -e trace=write,exit_group ./verifywrite(1, "prefix=qrc:/qt/qml/Hmi/Shell/ en"..., 141) = 141exit_group(0)                           = ?+++ exited with 0 +++

Packaging and AOT Compilation Pitfalls on Embedded Targets

Make qt_add_qml_module the sole packaging boundary across your embedded HMI repository. Every screen pack, reusable gauge library, and style module receives an explicit dotted URI, static property types, and loadFromModule() entry point so runtime .qml flash reads disappear completely.

In Lesson 1.2, we step inside those compiled QML components to trace how declarative property bindings construct a directed acyclic dependency graph, why imperative = assignments sever live updates, and how the engine halts cyclic binding loops.

Loading Loose Files or Hand-Written .qrc Paths Alongside qt_add_qml_module:

  • Symptom: App starts with blank screen (QQmlApplicationEngine failed to load component) or silently parses uncompiled .qml text twice.
  • Root Cause: Calling engine.load(QUrl("qrc:/Main.qml")) bypasses Qt 6's qrc:/qt/qml/<URI>/qmldir module registry and skips precompiled AOT lookup tables.
  • Fix: Remove manual .qrc files for QML, enable qt_standard_project_setup(REQUIRES 6.8), and call engine.loadFromModule("Hmi.Shell", "Main").

Declaring Generic property var or Unqualified Parent IDs in Hot Components:

  • Symptom: qmlsc emits Could not compile binding warnings and Cortex-A7 startup/scroll CPU usage spikes inside QV4::ExecutionEngine.
  • Root Cause: Without concrete types (int, real, string, or registered QML_ELEMENT classes) in .qmltypes, the AOT compiler cannot prove memory layout and falls back to boxed QVariant lookups.
  • Fix: Replace property var with concrete types or required property declarations and enforce qmllint -Werror in CMake.

Guided Practice

Trace the canonical qrc directory path, qmldir resource URI, and loadFromModule() arguments for a reusable industrial gauge module declared with URI Hmi.Instruments.Fluid containing qml/PressureDial.qml. Verify why malformed URIs such as Hmi..Fluid or /Hmi/Fluid must be rejected at CMake configuration time.

Independent Practice

Extend verify.cpp to read a table of 8 QML component specs, compute the percentage of total module bindings compiled as direct C++ (direct_cpp_bindings * 100 / total_bindings), and fail with a non-zero exit status whenever direct AOT coverage drops below 95%.

Verification Checks

quiz · 1 of 3

Why should an embedded Qt 6.8 HMI call QQmlApplicationEngine::loadFromModule("Hmi.Shell", "Main") instead of engine.load("/opt/hmi/qml/Main.qml")?

quiz · 2 of 3

Which build-time artifact gives qmllint and qmlsc static visibility into C++ and QML property types across a module?

quiz · 3 of 3

Under Qt 6 policy QTP0001 (qt_standard_project_setup(REQUIRES 6.8)), where does qt_add_qml_module(hmi_shell URI Hmi.Controls.Gauges ...) embed its qmldir?

Key takeaways

  • CMake qt_add_qml_module embeds QML units under canonical qrc:/qt/qml/<URI-path>/ resources, synthesizes qmldir and .qmltypes, and eliminates loose filesystem parsing during cold boot.
  • Calling QQmlApplicationEngine::loadFromModule("Hmi.Shell", "Main") resolves precompiled module types directly from the in-memory qrc:/qt/qml/ registry without scanning mutable flash directories.
  • Ahead-of-time qmlsc compilation requires complete .qmltypes metadata and explicit static property types so bindings compile into native C++ functions instead of interpreted QV4 bytecode.
  • Eliminating runtime QV4 JIT compilation on ARMv7-A Cortex-A7 avoids cold-start AST allocation spikes and removes writable-and-executable anonymous page pressure at boot.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure