Reactive Property Bindings, Dependency DAGs & Binding Loop Detection

Declarative QML property bindings look like ordinary value assignments, yet at runtime they maintain directed subscriber edges whose invariants shatter on imperative = writes or accidental parent-child geometry cycles.

25 minfree previewLinux 6.12→ module 1 lab
What you'll learn
  • Construct multi-hop reactive QML property bindings that propagate upstream NOTIFY changes cleanly across readonly intermediate nodes.
  • Diagnose frozen UI controls caused by imperative = assignments and preserve live bindings using Binding { when: ... } or Qt.binding().
  • Implement deterministic dependency propagation and direct/transitive BindingLoop cycle detection in ISO C++20.

How Declarative Bindings Wire Subscriber Edges and Why Imperative Writes Break Them

Writing barWidth: card.usableWidth * card.ratio with a colon (:) in QML does far more than compute an initial startup width. During component instantiation, the QML engine executes that expression inside a dependency-capture context: every read property carrying a NOTIFY signal registers a directed subscriber edge pointing at barWidth. Whenever rpm or card.width subsequently changes, the engine walks those downstream edges and updates barWidth automatically.

Two subtle defects break this mechanism in production HMIs. First, executing an imperative JavaScript assignment such as card.barWidth = 96 inside a touch handler permanently detaches and destroys the QQmlBinding object, leaving the gauge frozen on future rpm updates unless overridden declaratively via Binding { when: card.overrideActive; value: 96 } or restored with Qt.binding(). Second, wiring parent geometry from child width while child width depends on parent width creates a cycle that re-enters an active QQmlBinding and aborts with Binding loop detected.

fig_m01_l02_a.svg — Unidirectional QML binding DAG propagation versus…

Figure 1.2a. Unidirectional QML binding DAG propagation versus imperative '=' unbind and cycle faults.

mental model: A QML property binding behaves like a live spreadsheet formula cell (=B1*C1): changing B1 recomputes the cell automatically, typing a literal number (96) overwrites and deletes the formula, and referencing A1 inside B1 triggers an immediate circular-reference fault.

Where it stops working: Unlike spreadsheets that recalculate in deferred sheet-wide passes, QML evaluates dependent bindings synchronously along NOTIFY signal edges on the GUI thread unless coalesced via Binding { delayed: true }.

definition (Reactive Property-Binding Directed Acyclic Graph (DAG)): In the Qt QML engine, each colon (:) binding records upstream NOTIFY-capable properties read during expression evaluation as directed edges (upstream -> dependent), forming a directed acyclic graph (DAG) that must remain free of cycles to terminate deterministically.

ast_m01_l02.svg — Declarative ':' wires a live DAG edge; imperative '='…step 1/4
  1. Step 1. Evaluate the right-hand expression under dependency capture so upstream NOTIFY signals subscribe barWidth.
  2. Step 2. Propagate rpm updates along directed subscriber edges from rpm through ratio to barWidth.
  3. Step 3. Use declarative Binding { when: ... } or Qt.binding() instead of raw '=' so live tracking survives overrides.
  4. Step 4. Check each binding's active evaluating flag to halt direct or transitive cycles before stack overflow.

Figure 1.2b. Declarative ':' wires a live DAG edge; imperative '=' severs it; Binding { when } overrides safely.

Guarding Derived Formulas with readonly Properties and Declarative Binding Overrides

Inspect GaugeCard.qml below. Every property declares a concrete type (real, bool) so qmlsc compiles every expression into native C++, while intermediate values (usableWidth and ratio) are marked readonly property so accidental imperative = writes fail immediately during qmllint verification instead of silently corrupting runtime state.

Look at how manual test overrides are handled: rather than mutating barWidth imperatively in onClicked, the Binding element activates when: card.overrideActive with restoreMode: Binding.RestoreBindingOrValue. When overrideActive returns to false, Qt automatically restores the original card.usableWidth * card.ratio binding without manual Qt.binding() closures, and setting delayed: true on multi-input bindings coalesces burst updates to the end of the event-loop turn.

fig_m01_l02_b.svg — Reactive property node state fields and re-entrancy…

Figure 1.2b. Reactive property node state fields and re-entrancy cycle guard pipeline.

QML ConstructEffect on Active Binding AOT SupportRecommended Engineering Use
Colon prop: exprInstalls live QQmlBinding DAG edgesDirect C++ function callDefault unidirectional reactive UI state
readonly property real x: exprImmutable live binding; forbids =Direct C++ inline getterIntermediate derived ratios and layout bounds
Imperative prop = literalDestroys active QQmlBinding permanentlyCompiled write + unbindOnly for genuinely manual unbound state variables
Binding { target; property; when; delayed }Suspends & cleanly restores prior bindingFull static C++ supportModal overrides and burst-coalesced updates
learner@ksa: ~/gl-q03/m01-l02
learner@ksa:~/gl-q03/m01-l02$ bat -H 14 -H 19 GaugeCard.qml File: GaugeCard.qml    import QtQuick        Rectangle {        id: card        width: 344        height: 96        color: "#1c2128"            required property real rpm        property real maxRpm: 6000.0        property bool overrideActive: false        property real overridePx: 96.0          readonly property real usableWidth: Math.max(0.0, card.width - 24.0)        readonly property real ratio:            Math.min(1.0, Math.max(0.0, card.rpm / card.maxRpm))        property real barWidth: card.usableWidth * card.ratio          Binding {            target: card            property: "barWidth"            value: card.overridePx            when: card.overrideActive            restoreMode: Binding.RestoreBindingOrValue        }            Rectangle {            x: 12            y: 52            width: card.barWidth            height: 20            color: card.ratio > 0.85 ? "#e5534b" : "#3fb950"        }    }
  1. readonly intermediate properties prevent imperative '=' handlers from severing derived formulas.
  2. Binding { when: card.overrideActive } overrides barWidth temporarily and restores the live formula afterward.
QQmlBinding / Qt.binding / Binding(3qt-ksa) at a glance — GL-Q03
QQmlBinding / Qt.binding / Binding(3qt-ksa) GL-Q03 Quick Reference QQmlBinding / Qt.binding / Binding(3qt-ksa) NAME       Binding, Qt.binding -- QML reactive dependency DAG edges, overrides &       loop diagnostics SYNOPSIS       readonly property real ratio: Math.clamp(rpm / maxRpm, 0.0, 1.0)       Binding { target: item; property: "width"; value: 96; when: manual;       delayed: true } item.width = Qt.binding(function() { return       item.usableWidth * item.ratio })        DIAGNOSTICS & INVARIANTS QML Binding Loop : Triggered when evaluating       property A re-enters A (A -> ... -> A) QT_LOGGING_RULES :       "qt.qml.binding.removal.info=true" logs accidental '=' unbinds! Kernel Systems Academy Lesson 1.2  QQmlBinding / Qt.binding / Binding(3qt-ksa) GL-Q03 quick reference · full manual page: man 3qt-ksa QQmlBinding / Qt.binding / Binding 

Implementing a Cycle-Detecting Reactive Binding Graph in ISO C++20

To see the exact data structures behind QQmlBinding without hidden engine magic, verify.cpp implements ReactiveBindingDag in ISO C++20. Each property node owns its current double value, a bound flag, an evaluating re-entrancy guard, upstream deps, and downstream subs.

Notice how bind() snapshots saved state before invoking recompute(): if wiring a new expression closes either a direct 2-node loop (A <-> B) or a 3-node transitive cycle (A -> B -> C -> A), n.evaluating catches the re-entry immediately, detaches the offending edges, and restores the prior finite value cleanly.

learner@ksa: ~/gl-q03/m01-l02
learner@ksa:~/gl-q03/m01-l02$ bat -H 33 -H 66 verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cmath>    #include <cstdio>    #include <functional>    #include <vector>        class ReactiveBindingDag {     public:      int add_prop(double initial) {        nodes_.push_back(Node{initial, false, false, {}, nullptr, {}});        return static_cast<int>(nodes_.size() - 1);      }          bool bind(int id, std::vector<int> deps, std::function<double()> fn) {        double saved = nodes_[id].val;        detach_deps(id);        nodes_[id].deps = std::move(deps);        nodes_[id].fn = std::move(fn);        nodes_[id].bound = true;        for (int d : nodes_[id].deps) nodes_[d].subs.push_back(id);        if (!recompute(id)) {          detach_deps(id);          nodes_[id].fn = nullptr;          nodes_[id].bound = false;          nodes_[id].evaluating = false;          nodes_[id].val = saved;          return false;        }        return true;      }        void assign_literal(int id, double v) {        detach_deps(id);        nodes_[id].fn = nullptr;        nodes_[id].bound = false;        set_and_notify(id, v);      }          double get(int id) const { return nodes_[id].val; }      bool is_bound(int id) const { return nodes_[id].bound; }         private:      struct Node {        double val;        bool bound;        bool evaluating;        std::vector<int> deps;        std::function<double()> fn;        std::vector<int> subs;      };      std::vector<Node> nodes_;          void detach_deps(int id) {        for (int d : nodes_[id].deps) {          auto& s = nodes_[d].subs;          s.erase(std::remove(s.begin(), s.end(), id), s.end());        }        nodes_[id].deps.clear();      }          bool recompute(int id) {        Node& n = nodes_[id];        if (!n.bound) return true;        if (n.evaluating) return false;      n.evaluating = true;        double next = n.fn();        bool ok = set_and_notify(id, next);        n.evaluating = false;        return ok;      }          bool set_and_notify(int id, double v) {        if (std::abs(nodes_[id].val - v) < 1e-9) return true;        nodes_[id].val = v;        std::vector<int> copy = nodes_[id].subs;        for (int sub : copy) {          if (!recompute(sub)) return false;        }        return true;      }    };        int main() {      ReactiveBindingDag g;      int width = g.add_prop(344.0);      int rpm = g.add_prop(3000.0);      int max_rpm = g.add_prop(6000.0);      int usable = g.add_prop(0.0);      int ratio = g.add_prop(0.0);      int bar_w = g.add_prop(0.0);          assert(g.bind(usable, {width}, [&] { return g.get(width) - 24.0; }));      assert(g.bind(ratio, {rpm, max_rpm}, [&] {        return std::clamp(g.get(rpm) / g.get(max_rpm), 0.0, 1.0);      }));      assert(g.bind(bar_w, {usable, ratio}, [&] {        return g.get(usable) * g.get(ratio);      }));      assert(std::abs(g.get(bar_w) - 160.0) < 1e-6);          g.assign_literal(rpm, 4500.0);      assert(std::abs(g.get(bar_w) - 240.0) < 1e-6);          g.assign_literal(bar_w, 96.0);      assert(!g.is_bound(bar_w));      g.assign_literal(rpm, 6000.0);      assert(std::abs(g.get(bar_w) - 96.0) < 1e-6);          assert(g.bind(bar_w, {usable, ratio}, [&] {        return g.get(usable) * g.get(ratio);      }));      assert(std::abs(g.get(bar_w) - 320.0) < 1e-6);          int a = g.add_prop(10.0), b = g.add_prop(0.0), c = g.add_prop(0.0);      assert(g.bind(b, {a}, [&] { return g.get(a) + 2.0; }));      assert(g.bind(c, {b}, [&] { return g.get(b) * 2.0; }));      assert(!g.bind(a, {c}, [&] { return g.get(c) - 1.0; }));      assert(!g.is_bound(a) && std::abs(g.get(a) - 10.0) < 1e-6);          std::printf("live_bar=240.0 unbind_frozen=96.0 rebound_bar=%.1f cycle_guard=ok\n",                  g.get(bar_w));      return 0;    }
  1. assign_literal detaches upstream subscriber edges and clears bound, reproducing QML imperative '=' behavior.
  2. If n.evaluating is already true, evaluation has cycled back into an active node (BindingLoop abort).

Tracing Live Propagation, Imperative Unbinding, and Cycle Rejection

Confirm each transition in the recorded ./verify output. At rpm = 3000, bar_w evaluates to 160.0; raising rpm to 4500 propagates across ratio to 240.0. Calling assign_literal(bar_w, 96.0) detaches bar_w so rpm = 6000 leaves it frozen at 96.0, until rebinding restores 320.0.

Finally, wiring the 3-node loop a -> b -> c -> a trips n.evaluating == true on a, rolls back the cyclic edge, and preserves a == 10.0 with exit code 0 under strace. On real Qt targets, enabling QT_LOGGING_RULES="qt.qml.binding.removal.info=true" logs accidental = unbinds live.

learner@ksa: ~/gl-q03/m01-l02
learner@ksa:~/gl-q03/m01-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q03/m01-l02./verifylive_bar=240.0 unbind_frozen=96.0 rebound_bar=320.0 cycle_guard=oklearner@ksa:~/gl-q03/m01-l02
strace — learner@ksa: ~/gl-q03/m01-l02
learner@ksa:~/gl-q03/m01-l02strace -e trace=write,exit_group ./verifywrite(1, "live_bar=240.0 unbind_frozen=96."..., 67) = 67exit_group(0)                           = ?+++ exited with 0 +++

Common Reactive Binding Bugs in Embedded Dashboards

Nearly every "stuck needle" or mysterious layout jitter in Qt Quick dashboards stems from violating DAG discipline: either an imperative = handler severed a declarative binding, or bidirectional parent-child sizing created a hidden cycle.

In Lesson 1.3, we connect high-rate C++20 sensor models into this DAG using QML_ELEMENT, Q_PROPERTY(... FINAL), and deadband signal coalescing so qmlsc emits direct C++ getter calls.

Bidirectional Parent-Child implicitWidth / width Dependencies:

  • Symptom: Console floods with QML Rectangle: Binding loop detected for property "width" and text labels clip randomly.
  • Root Cause: Container width: childRow.width + 16 while childRow.width: parent.width - 16 forms a 2-node dependency cycle.
  • Fix: Size containers down from outer Layout or explicit bounds (width), and size children up strictly via implicitWidth.

Overwriting Bound Properties Imperatively Inside Component.onCompleted or Signal Slots:

  • Symptom: Gauge initializes to 0 on boot and never responds to live C++ NOTIFY signals afterward.
  • Root Cause: Writing gauge.value = 0 in Component.onCompleted runs after binding setup and deletes the declarative : binding.
  • Fix: Initialize default values inside the C++ model or use Binding { when: ...; restoreMode: Binding.RestoreBindingOrValue }.

Guided Practice

Sketch the directed dependency edges for a BatteryIndicator.qml component exposing required property real soc, readonly property bool lowAlarm: soc < 15.0, and color: lowAlarm ? "#e5534b" : "#3fb950". Explain what happens if a MouseArea executes onClicked: color = "#ffffff" and how to express a momentary press highlight without destroying the lowAlarm color binding.

Independent Practice

Extend ReactiveBindingDag in verify.cpp with a delayed_batch queue mode that records dirty downstream node IDs while begin_batch() is active and evaluates each affected node at most once in topological depth order inside end_batch(), even when both width and rpm change together.

Verification Checks

quiz · 1 of 3

In GaugeCard.qml, why would executing card.barWidth = 96 inside onClicked freeze the gauge on subsequent rpmChanged() signals?

quiz · 2 of 3

How does the Qt QML runtime detect a Binding loop across conditional or multi-item property expressions?

quiz · 3 of 3

What problem does setting delayed: true on a QML Binding element solve?

Key takeaways

  • A declarative colon (:) property binding registers live upstream NOTIFY subscriber edges in the QML evaluation DAG, whereas an imperative JavaScript = assignment permanently destroys that binding.
  • While evaluating a QQmlBinding, the QML engine sets an active re-entrancy flag on the node and aborts with a Binding loop detected warning if evaluation re-enters an already active binding.
  • Configuring Binding with delayed set to true or conditional when clauses coalesces rapid multi-property bursts and applies temporary overrides without destroying the underlying declarative binding.
  • Marking intermediate derived formulas readonly property prevents accidental imperative = overwrites at both qmllint build time and QML runtime.
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure