learner@ksa:~/gl-q01$

>_ Kernel Systems Academy

Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets

Embedded Linux, C/C++, and instrumentation engineers building Qt 6 HMIs

Outcome: Architect, instrument, and verify leak-free ISO C++20 and Qt 6.8 Widgets HMIs from QObject meta-object internals through Model/View tables, QSaveFile persistence, custom QPainter gauges, and QTest suites.

6 modules18 lessons6 labsLinux 6.12 · C++20
  1. m01/ C++20 Toolchain, RAII Lifetimes & QObject Ownership Trees
  2. m02/ Qt 6 PIMPL ABI, Designer uic Forms & moc Meta-Object Tables
  3. m03/ PMF Signal Lifetimes, Event Filters & Monotonic Timers
  4. m04/ Button Interlocks, Input Validators & Geometry Layout Solvers
  5. m05/ Container Widgets, QAbstractItemModel Roles & Proxy Views
  6. m06/ QSaveFile Persistence, QPainter/QtCharts & QTest CI
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets1/570

m01/

>_ Kernel Systems Academy

C++20 Toolchain, RAII Lifetimes & QObject Ownership Trees

Enforce strict ISO C++20 compilation, target-scoped CMake AUTOMOC/AUTOUIC/AUTORCC code generation, deterministic RAII versus QObject parent-child lifetimes, and hybrid virtual-boundary plus C++20 concept polymorphism.

  1. 1.1 ISO C++20 Flags, CMake AUTOMOC & Translation-Unit Hygiene
  2. 1.2 RAII, Rule of Five & QObject Parent-Child Ownership Trees
  3. 1.3 Virtual Dispatch, Inheritance, Operator Overloads & C++20 Concepts

lab → C++20 RAII Move Guards, Intrusive QObject Tree Cycles & deleteLater Sweep

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets2/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

ISO C++20 Flags, CMake AUTOMOC & Translation-Unit Hygiene

free preview25 min

What you'll learn

  • Configure target-scoped CMake 3.28+ properties enforcing strict ISO C++20 without GNU extensions alongside AUTOMOC, AUTOUIC, and AUTORCC.
  • Diagnose missing vtable linker errors triggered when Q_OBJECT classes live privately inside .cpp files or outside AUTOMOC target sources.
  • Quantify preprocessor and incremental rebuild fan-out reductions achieved by replacing <QtWidgets> umbrella includes with forward declarations.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets3/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Legacy Global Build Macros Break Incremental Qt 6 Builds

  • Industrial HMIs built on Qt 6.8 LTS require at least C++17 and gain concepts, std::span, and three-way…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets4/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Legacy Global Build Macros Break Incremental Qt 6 Builds

  • Before g++ compiles any QObject translation unit, three code generators execute inside the build graph.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets5/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Legacy Global Build Macros Break Incremental Qt 6 Builds

fig_m01_l01_a.svg

Figure 1.1a: Target-scoped CMake properties isolate moc, uic, and rcc generation per binary while keeping strict ISO C++20 flags off vendor headers.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets6/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Mental model

note: Think of a target-scoped CMake build graph like a keyed CNC machining fixture on an assembly line: raw castings (panel.hpp, panel.ui, icons.qrc) pass through dedicated prep stations (moc, uic, rcc) whose output jigs lock solely onto one part number (ksa_hmi), rather than dumping unlabelled shims across the entire factory floor.

Where it stops working: Physical fixtures visibly jam when mismatched bolts are mixed, whereas combining static C++ archives compiled under incompatible standard flags or missing Q_OBJECT meta-tables passes object compilation quietly and explodes only during final ELF symbol resolution.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets7/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

CMAKE_AUTOMOC and Imported CMake Targets

definition: CMAKE_AUTOMOC (activating target property AUTOMOC ON) instructs CMake to synthesize a <target>_autogen pre-build rule that scans target headers and sources for Q_OBJECT, Q_GADGET, or Q_NAMESPACE, invokes Qt's Meta-Object Compiler (moc), and bundles public header outputs into mocs_compilation.cpp. Imported targets (Qt6::Core, Qt6::Gui, Qt6::Widgets) are read-only CMake graph nodes exported by Qt6Config.cmake carrying exact shared-library paths alongside INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_COMPILE_FEATURES.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets8/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Legacy Global Build Macros Break Incremental Qt 6 Builds

Lock CXX_STANDARD 20, CXX_STANDARD_REQUIRED ON, and CXX_EXTENSIONS OFF directly on the HMI target.

Use target-scoped CMake properties, forward declarations, and explicit .moc includes.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets9/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Inside Autogen Artifact Layout and Header Dependency Fan-Out

  • When Ninja or GNU Make builds target ksa_hmi, CMake creates ksa_hmi_autogen/include/ for generated head…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets10/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Inside Autogen Artifact Layout and Header Dependency Fan-Out

  • Header discipline matters just as much on multi-core build servers and embedded cross-toolchains.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets11/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Inside Autogen Artifact Layout and Header Dependency Fan-Out

fig_m01_l01_b.svg

Figure 1.1b: Separating header moc compilation, inline .moc includes, ui_*.h forms, and qrc_*.cpp arrays prevents mystery link errors.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets12/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

CMakeLists.txt

learner@ksa: ~/gl-q01/m01-l01
learner@ksa:~/gl-q01/m01-l01$ bat CMakeLists.txt File: CMakeLists.txt    cmake_minimum_required(VERSION 3.28)    project(ksa_hmi VERSION 1.0.0 LANGUAGES CXX)        find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets Test)        add_executable(ksa_hmi        src/main.cpp        src/panel_window.hpp        src/panel_window.cpp        src/panel_window.ui        resources/icons.qrc    )        set_target_properties(ksa_hmi PROPERTIES
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets13/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

cmake-qt

cmake-qt(7) at a glance — GL-Q01
cmake-qt(7)                 GL-Q01 Quick Reference                 cmake-qt(7) NAME       cmake-qt - CMake target properties for Qt 6 moc, uic, and rcc       automation SYNOPSIS       find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets)       set_target_properties(<tgt> PROPERTIES AUTOMOC ON AUTOUIC ON AUTORCC       ON) target_link_libraries(<tgt> PRIVATE Qt6::Core Qt6::Gui       Qt6::Widgets) DESCRIPTION       AUTOMOC scans target headers (.h/.hpp) for Q_OBJECT/Q_GADGET and       compiles mocs_compilation.cpp. If a .cpp file declares a private       Q_OBJECT class, end that file with #include "<stem>.moc". AUTOUIC       compiles <name>.ui into ui_<name>.h. AUTORCC compiles .qrc manifests       into C++ static byte arrays. Kernel Systems Academy                   m01-l01                   cmake-qt(7) GL-Q01 quick reference · full manual page: man 7 cmake-qt 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets14/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Modeling CMake Autogen and Rebuild Fan-Out in Host C++20

  • Even on a headless CI container without full X11/Wayland packages installed, we can verify every `cmake_aut…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets15/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Modeling CMake Autogen and Rebuild Fan-Out in Host C++20

  • Second, estimate_preprocessed_kloc() models a 6-unit HMI project comparing a header that includes `<QtWid…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets16/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m01-l01
learner@ksa:~/gl-q01/m01-l01$ bat verify.cpp File: verify.cpp    #include <cassert>    #include <cstdio>    #include <string>    #include <string_view>    #include <vector>        namespace hmi_build {        struct SourceUnit {        std::string path;        bool has_q_object;        bool has_dot_moc_include;        bool pulls_umbrella_qtwidgets;        int client_tus;
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets17/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Inspecting Autogen Audit Metrics and System Call Output

  • Confirm that ./verify prints clean(hdr=2 inline=1 err=0 kloc=84) versus `broken(err=1 umbrella=2 kloc=1…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets18/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Inspecting Autogen Audit Metrics and System Call Output

  • Inspect the strace output below as well: the compiled C++20 binary flushes its formatted summary in one `…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets19/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Inspecting Autogen Audit Metrics and System Call Output

learner@ksa: ~/gl-q01/m01-l01
learner@ksa:~/gl-q01/m01-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m01-l01./verifyAUTOMOC clean(hdr=2 inline=1 err=0 kloc=84) broken(err=1 umbrella=2 kloc=1680)learner@ksa:~/gl-q01/m01-l01
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets20/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Inspecting Autogen Audit Metrics and System Call Output

strace — learner@ksa: ~/gl-q01/m01-l01
learner@ksa:~/gl-q01/m01-l01strace -e trace=write,exit_group ./verifywrite(1, "AUTOMOC clean(hdr=2 inline=1 err"..., 79) = 79exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets21/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Build-Graph and Meta-Object Linker Pitfalls

  • Whenever ld fails with undefined reference to vtable for MyWidget or `undefined reference to MyWidget::…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets22/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Build-Graph and Meta-Object Linker Pitfalls

  • With strict -std=c++20, PRIVATE warning flags, imported Qt6::* targets, and forward-declared headers…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets23/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Adding Q_OBJECT to a previously plain class StatusCard : public QWidget compiles status_card.cpp.o cleanly, then fails at link time with undefined reference to vtable for StatusCard. - Root Cause: Declaring Q_OBJECT injects virtual declarations (metaObject(), qt_metacall()) whose out-of-line definitions live only inside moc_status_card.cpp; if the header was omitted from add_executable or build stamps were bypassed, moc never emitted those bodies. - Fix: List every .hpp file explicitly in add_executable / add_library alongside .cpp files and re-run cmake --build so <target>_autogen regenerates mocs_compilation.cpp.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets24/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Upgrading GCC on a developer workstation breaks third-party consumers or generated test harnesses with -Werror=deprecated-declarations inside external headers. - Root Cause: Passing -Wall -Wextra -Werror under PUBLIC or INTERFACE in target_compile_options forces strict warning-as-error flags onto every downstream consumer target. - Fix: Scope strict warning flags (-Wall -Wextra -Werror -pedantic) as PRIVATE on each owned target and ensure external SDK paths enter as SYSTEM interface includes (which Qt6::* imported targets do automatically).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets25/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Guided Practice

  • Extend SourceUnit in verify.cpp with a boolean in_target_sources field and verify what happens when a…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets26/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Independent Practice

  • Audit an existing C++ or qmake .pro HMI directory layout and draft a clean CMakeLists.txt splitting p…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets27/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Quick check

An engineer defines class PollWorker : public QObject { Q_OBJECT ... }; privately inside poller.cpp on a target with AUTOMOC ON, and linking fails with undefined reference to vtable for PollWorker. What fixes the build?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets28/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Quick check

Why should panel_window.hpp write class QPushButton; instead of #include <QtWidgets> when PanelWindow only stores QPushButton *m_armButton;?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets29/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Quick check

Which CMake target property trio enforces strict ISO C++20 without GNU extensions on ksa_hmi?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets30/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Summary

  • Enabling CMAKE_AUTOMOC, CMAKE_AUTOUIC, and CMAKE_AUTORCC as target properties schedules moc, uic, and rcc in the CMake build graph automatically whenever headers, .ui forms, or .qrc manifests change.
  • Linking imported targets such as Qt6::Widgets via target_link_libraries propagates transitive include paths, compile definitions, and -fPIC flags without polluting unrelated targets like legacy .pro globals.
  • Declaring a private Q_OBJECT subclass directly inside worker.cpp requires #include "worker.moc" at the bottom of worker.cpp because mocs_compilation.cpp cannot see translation-unit-local types.
  • Forward-declaring pointer members (class QPushButton;) in widget headers instead of pulling the <QtWidgets> umbrella header isolates downstream translation units from massive preprocessor token fan-out.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets31/570

GL-Q01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Key takeaways

  • Linking imported targets such as Qt6::Widgets via target_link_libraries propagates transitive include paths, compile definitions, and -fPIC flags without polluting unrelated targets like legacy .pro globals.
  • Declaring a private Q_OBJECT subclass directly inside worker.cpp requires #include "worker.moc" at the bottom of worker.cpp because mocs_compilation.cpp cannot see translation-unit-local types.
  • Forward-declaring pointer members (class QPushButton;) in widget headers instead of pulling the <QtWidgets> umbrella header isolates downstream translation units from massive preprocessor token fan-out.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets32/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

RAII, Rule of Five & QObject Parent-Child Ownership Trees

free preview30 min

What you'll learn

  • Implement a noexcept Rule-of-Five RAII guard in namespace hmi using std::exchange and self-move protection for non-QObject kernel handles.
  • Trace exact C++ destructor ordering across derived members, base ~QObject(), and intrusive child widget lists.
  • Eliminate heap corruption caused by stack-allocated child QObject ordering errors or dual std::unique_ptr + QObject parenting.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets33/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Two Competing Lifetime Models Inside One C++20 Binary

  • Modern ISO C++20 centers memory safety on lexical RAII (Resource Acquisition Is Initialization) and `std:…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets34/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Two Competing Lifetime Models Inside One C++20 Binary

  • Collision occurs when engineers mix automatic stack lifetimes or std::unique_ptr with QObject parenting…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets35/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Two Competing Lifetime Models Inside One C++20 Binary

fig_m01_l02_a.svg

Figure 1.2a: Every QObject with a non-null parent must be heap-allocated; non-QObject descriptors belong in Rule-of-Five RAII guards.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets36/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Mental model

note: A QObject parent works like a 19-inch industrial instrument rack: bolting heap-allocated modules (new QLabel(this)) into the rack means decommissioning the rack frame automatically disposes of every module still mounted inside, while unbolting and scrapping one module early cleanly empties its slot.

Where it stops working: Bolting a floor-welded transformer into a movable rack is physically impossible, whereas C++ happily lets you pass the address of a stack-allocated QLabel (&lbl) into QWidget* parenting APIs because QLabel* carries zero type-system distinction between stack and heap storage.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets37/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

RAII, Rule of Five, and Q_DISABLE_COPY_MOVE

definition: Coined by Bjarne Stroustrup, RAII (Resource Acquisition Is Initialization) binds resource acquisition to a constructor and release to the matching destructor so stack unwinding leaks nothing even across early returns. When a low-level wrapper directly manages a raw handle like a POSIX descriptor, C++20's Rule of Five defines the destructor, deleted copy constructor/assignment, and noexcept move constructor/assignment. QObject invokes Q_DISABLE_COPY_MOVE(Class) to delete all four copy/move operations, enforcing stable address identity in parent-child trees.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets38/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Two Competing Lifetime Models Inside One C++20 Binary

Wrap POSIX file descriptors or buffers in a Rule-of-Five guard that neutralizes moved-from state to -1.

Use Rule-of-Five/unique_ptr for roots and OS handles; use heap + parent this for child QObjects.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets39/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Destructor Execution Sequence Across Derived Members and QObjectPrivate

  • Let us trace the exact ISO C++20 teardown sequence of hmi::AlarmBanner in panel_owner.cpp below.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets40/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Destructor Execution Sequence Across Derived Members and QObjectPrivate

  • Now imagine what happens if an engineer mistakenly declares std::unique_ptr<QLabel> m_status initialized…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets41/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Destructor Execution Sequence Across Derived Members and QObjectPrivate

fig_m01_l02_b.svg

Figure 1.2b: Derived members unwind before ~QObject(), explaining why raw child pointers pair cleanly with parent-owned heap widgets.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets42/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

panel_owner.cpp

learner@ksa: ~/gl-q01/m01-l02
learner@ksa:~/gl-q01/m01-l02$ bat panel_owner.cpp File: panel_owner.cpp    #include <QLabel>    #include <QPushButton>    #include <QVBoxLayout>    #include <QWidget>    #include <unistd.h>    #include <utility>        namespace hmi {        class FdGuard {    public:        explicit FdGuard(int fd = -1) noexcept : m_fd(fd) {}        ~FdGuard() { reset(); }
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets43/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

QObject-ownership

QObject-ownership(3qt) at a glance — GL-Q01
QObject-ownership(3qt)      GL-Q01 Quick Reference      QObject-ownership(3qt) NAME       QObject, Q_DISABLE_COPY_MOVE - intrusive parent-child object tree       lifetimes SYNOPSIS       explicit QObject(QObject *parent = nullptr);       virtual ~QObject();       const QObjectList &QObject::children() const;       void QObject::setParent(QObject *parent); OWNERSHIP CONTRACT       1. Constructing QObject(parent) appends 'this' to parent's children()       list. 2. ~QObject() deletes every remaining child in children(), then       removes 'this' from its own parent (if still attached) and emits       destroyed(QObject *). 3. Copy/move construction and assignment are       deleted via Q_DISABLE_COPY_MOVE. Kernel Systems Academy             m01-l02              QObject-ownership(3qt) GL-Q01 quick reference · full manual page: man 3qt QObject-ownership 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets44/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Proving RAII Move Semantics and Tree Unwinding in Host C++20

  • In verify.cpp, we build hmi::MoveHandle and an intrusive hmi::ObjectNode tree in strict ISO C++20 to…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets45/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Proving RAII Move Semantics and Tree Unwinding in Host C++20

  • Study lines 47-56 of verify.cpp: popping child from m_children and setting `child->m_parent = nullptr…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets46/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m01-l02
learner@ksa:~/gl-q01/m01-l02$ bat verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cstdio>    #include <memory>    #include <string>    #include <utility>    #include <vector>        namespace hmi {        class MoveHandle {    public:        MoveHandle(int fd, int *closes) noexcept : m_fd(fd), m_closes(closes) {}        ~MoveHandle() { reset(); }
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets47/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Verifying Heap Teardown Order and Allocator System Calls

  • Check ./verify output: RAII closes=1 teardown=early->btn->label->root stack_faults=1.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets48/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Verifying Heap Teardown Order and Allocator System Calls

  • Notice in strace how brk() establishes the C++ process heap arena once at startup, followed by all `new…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets49/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Verifying Heap Teardown Order and Allocator System Calls

learner@ksa: ~/gl-q01/m01-l02
learner@ksa:~/gl-q01/m01-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m01-l02./verifyRAII closes=1 teardown=early->btn->label->root stack_faults=1learner@ksa:~/gl-q01/m01-l02
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets50/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Verifying Heap Teardown Order and Allocator System Calls

strace — learner@ksa: ~/gl-q01/m01-l02
learner@ksa:~/gl-q01/m01-l02strace -e trace=brk,write,exit_group ./verifybrk(NULL)                               = 0x6550aa822000brk(NULL)                               = 0x6550aa822000brk(0x6550aa843000)                     = 0x6550aa843000write(1, "RAII closes=1 teardown=early->bt"..., 62) = 62exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets51/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Ownership Collisions in Production Qt 6 Codebases

  • Keep the ownership line razor-sharp in every code review: if an object inherits QObject and has a parent,…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets52/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Ownership Collisions in Production Qt 6 Codebases

  • Notice how Q_DISABLE_COPY_MOVE turns accidental value-copy bugs (void showPanel(QWidget w)) into immedi…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets53/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Clicking a 'Close Card' QPushButton inside CardWidget triggers delete this; in the slot and crashes immediately inside QAbstractButton::mouseReleaseEvent after the slot returns. - Root Cause: CardWidget is the parent of the QPushButton currently executing on the C++ call stack! Synchronous delete this destroys the child QPushButton while QPushButton's own member function is still active on the stack. - Fix: Call this->deleteLater() instead of delete this inside slots or event handlers so Qt posts a QEvent::DeferredDelete ticket processed safely after the active call stack unwinds.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets54/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: An engineer stores std::unique_ptr<QPushButton> m_btn = std::make_unique<QPushButton>("Run"); (initially parentless) and calls layout->addWidget(m_btn.get()), causing a double-free crash on window close. - Root Cause: QLayout::addWidget() automatically calls setParent() to reparent m_btn.get() onto the layout's host QWidget, silently creating dual ownership alongside m_btn! - Fix: Allocate layout-managed widgets with new QPushButton(tr("Run"), this) (or transfer ownership via m_btn.release()) and keep only a non-owning QPushButton * observer pointer.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets55/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Guided Practice

  • Modify verify.cpp to test the reverse stack declaration order: `{ ObjectNode parent("p", nullptr, false,…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets56/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Independent Practice

  • Write a C++20 Rule-of-Five MmapRegion class wrapping a void * pointer and std::size_t byte length wit…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets57/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Quick check

What happens at the closing brace of { QLabel lbl; QWidget win; lbl.setParent(&win); } under standard C++20 stack unwinding?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets58/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Quick check

Why does AlarmBanner hold QLabel *m_status as a raw pointer instead of std::unique_ptr<QLabel> when initialized with new QLabel(tr("Nominal"), this)?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets59/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Quick check

Inside FdGuard::operator=(FdGuard &&other), why must if (this != &other) guard reset()?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets60/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Summary

  • Destroying a parent QObject walks QObjectPrivate::children and calls delete on remaining children, so parenting a stack-allocated child onto a shorter-lived stack parent causes a fatal invalid-free crash.
  • QObject deletes its copy constructor and copy-assignment operator (Q_DISABLE_COPY_MOVE) because tree identity, this parent links, and live signal connections cannot be meaningfully cloned.
  • Deleting a heap-allocated child QObject before its parent executes ~QObject(), which removes this from the parent's children list immediately so the parent never double-deletes it later.
  • Production C++20 widgets follow the Rule of Zero by delegating POSIX descriptors to Rule-of-Five RAII guards (std::exchange move transfer) while storing this-parented child widgets as raw non-owning pointers.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets61/570

GL-Q01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Key takeaways

  • QObject deletes its copy constructor and copy-assignment operator (Q_DISABLE_COPY_MOVE) because tree identity, this parent links, and live signal connections cannot be meaningfully cloned.
  • Deleting a heap-allocated child QObject before its parent executes ~QObject(), which removes this from the parent's children list immediately so the parent never double-deletes it later.
  • Production C++20 widgets follow the Rule of Zero by delegating POSIX descriptors to Rule-of-Five RAII guards (std::exchange move transfer) while storing this-parented child widgets as raw non-owning pointers.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets62/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Virtual Dispatch, Inheritance, Operator Overloads & C++20 Concepts

free preview30 minlab lab_m01_cpp20_qobject_raii

What you'll learn

  • Measure exact object size (sizeof) growth from vptr insertion and verify base-pointer polymorphic teardown via virtual destructors.
  • Implement constexpr C++20 value-type operator overloads (operator<=>, operator==, operator+) cleanly separated from identity-based QObject classes.
  • Partition high-rate C++20 concept-constrained sample filters from non-templated QObject presenters and benchmark dispatch latency with CLOCK_MONOTONIC.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets63/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Dynamic Widget Polymorphism Meets Zero-Overhead C++20 Static Constraints

  • Every QObject instance begins in memory with a hidden virtual table pointer (vptr: 8 bytes on LP64 `x86…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets64/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Dynamic Widget Polymorphism Meets Zero-Overhead C++20 Static Constraints

  • Simultaneously, moc enforces a hard architectural rule: a Q_OBJECT class cannot be a class template (`t…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets65/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Dynamic Widget Polymorphism Meets Zero-Overhead C++20 Static Constraints

fig_m01_l03_a.svg

Figure 1.3a: Keep arithmetic and filtering in constexpr value types and C++20 concepts; cross into vtable/QObject dispatch only at frame cadence.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets66/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Mental model

note: Dynamic vtable dispatch works like routing calls through a live telephone switchboard where any extension can be patched to a new desk at runtime, whereas a C++20 concept acts like a precision-keyed waveguide machined directly into the chassis after verifying flange dimensions on the blueprint.

Where it stops working: A machined waveguide cannot re-route to a plugin loaded at runtime via dlopen(), so genuinely heterogeneous runtime collections—such as child widgets in a layout or swappable hardware backends—still require a vptr and a virtual base destructor.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets67/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

vptr, vtable, and C++20 Concepts

definition: Under the Itanium C++ ABI used on Linux (x86_64 and ARMv7-A), every polymorphic object stores a hidden vptr at byte offset 0 addressing a compiler-generated read-only vtable containing RTTI metadata and function pointers for virtual methods and deleting/complete destructors. A C++20 concept is a named compile-time boolean predicate (requires(...)) over template parameters that validates syntactic and type requirements at instantiation time with clear diagnostics and zero runtime storage or indirection.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets68/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Dynamic Widget Polymorphism Meets Zero-Overhead C++20 Static Constraints

Declare a public virtual destructor on every abstract base class deleted through a base pointer.

Use virtual + override/final for runtime plugins/widgets, and C++20 concepts + <=> for hot data.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets69/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Inside Itanium C++ ABI Object Layout and Concept Instantiation

  • Inspect telemetry_sink.hpp below.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets70/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Inside Itanium C++ ABI Object Layout and Concept Instantiation

  • Next, look at how TelemetryPresenter works around moc's no-class-template rule: TelemetryPresenter it…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets71/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Inside Itanium C++ ABI Object Layout and Concept Instantiation

fig_m01_l03_b.svg

Figure 1.3b: Adding the first virtual function inserts an 8-byte vptr (plus alignment padding) on LP64 hosts or 4 bytes on ARMv7-A.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets72/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

telemetry_sink.hpp

learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03$ bat telemetry_sink.hpp File: telemetry_sink.hpp    #pragma once    #include <QObject>    #include <compare>    #include <concepts>    #include <cstdint>    #include <span>        namespace hmi {        struct MilliVolts {        std::int32_t mv = 0;            constexpr auto operator<=>(const MilliVolts &) const noexcept = default;        constexpr MilliVolts operator+(MilliVolts rhs) const noexcept {
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets73/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

cpp20-polymorphism

cpp20-polymorphism(7) at a glance — GL-Q01
cpp20-polymorphism(7)       GL-Q01 Quick Reference       cpp20-polymorphism(7) NAME       virtual, override, final, concept, operator<=> - C++20 dispatch & value       contracts SYNOPSIS       struct Unit { int v; constexpr auto operator<=>(const Unit&) const noexcept = default; };       template <typename T> concept Sink = requires(T s, int x) { { s.push(x) } noexcept; };       class Base { public: virtual ~Base() = default; virtual void run() = 0; };       class Leaf final : public Base { public: void run() override; }; RULES       1. Any base class deleted via Base* MUST declare a public virtual       destructor. 2. Mark every overridden virtual method 'override' to catch       signature drift. 3. moc forbids class templates with Q_OBJECT, but       allows member function templates. Kernel Systems Academy              m01-l03              cpp20-polymorphism(7) GL-Q01 quick reference · full manual page: man 7 cpp20-polymorphism 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets74/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Verifying vptr Footprint, Operator<=>, and Concept Dispatch in C++20

  • In verify.cpp, we prove four C++20 invariants quantitatively: (1) MilliVolts (sizeof == 4) supports `…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets75/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Verifying vptr Footprint, Operator<=>, and Concept Dispatch in C++20

  • Notice that correctness assertions check exact mathematical sums (50500 mV) and destructor counts (1/1)…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets76/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03$ bat verify.cpp File: verify.cpp    #include <algorithm>    #include <array>    #include <cassert>    #include <compare>    #include <concepts>    #include <cstdint>    #include <cstdio>    #include <ctime>    #include <memory>        namespace hmi {        struct MilliVolts {        std::int32_t mv = 0;
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets77/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Confirming vptr Size Growth and Polymorphic Teardown

  • Verify ./verify output: sizeof_mv=4 vptr=+8b dtors=1/1 on 64-bit Linux, followed by median virt_p50 a…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets78/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Confirming vptr Size Growth and Polymorphic Teardown

  • Notice in strace that clock_gettime(CLOCK_MONOTONIC) resolves via the Linux kernel vDSO shared page…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets79/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Confirming vptr Size Growth and Polymorphic Teardown

learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m01-l03./verifysizeof_mv=4 vptr=+8b dtors=1/1 virt_p50=85951ns conc_p50=85990nslearner@ksa:~/gl-q01/m01-l03
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets80/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Confirming vptr Size Growth and Polymorphic Teardown

strace — learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03strace -e trace=write,exit_group ./verifywrite(1, "sizeof_mv=4 vptr=+8b dtors=1/1 v"..., 66) = 66exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets81/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Polymorphic Slicing, Overload Hiding, and moc Template Limits

  • Module 1 has established your C++20 and QObject architectural foundation: isolated target CMake autogen g…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets82/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Polymorphic Slicing, Overload Hiding, and moc Template Limits

  • Now put all three lessons into practice in the lab_m01_cpp20_qobject_raii engineering studio below, where…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets83/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Subclassing QWidget and writing void keyPressEvent(const QKeyEvent *e) (adding an extra const!) compiles with zero errors, yet pressing keys on the widget never invokes the handler. - Root Cause: QWidget::keyPressEvent(QKeyEvent *event) takes a non-const pointer; without override, C++ treats keyPressEvent(const QKeyEvent *) as a brand-new unrelated overload rather than overriding the vtable slot! - Fix: Append override to every virtual override in derived classes (void keyPressEvent(QKeyEvent *event) override;) so signature mismatches fail compilation immediately.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets84/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Writing template <typename T> class SensorPlot : public QWidget { Q_OBJECT ... }; fails during the AUTOMOC step with Error: Template classes not supported by Q_OBJECT. - Root Cause: moc parses headers once before C++ template instantiation and cannot emit concrete staticMetaObject symbols for arbitrary future template arguments T. - Fix: Factor signals, slots, and Q_OBJECT into a non-templated base or presenter class (SensorPlotBase), or make only the non-signal ingestion helper a member function template (template <SampleFilter F> void ingest(F &)).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets85/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Guided Practice

  • Add a second SampleFilter-conforming struct ClampedFilter to verify.cpp that clamps each incoming `Mi…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets86/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Independent Practice

  • Open labs/lab_m01_cpp20_qobject_raii/ and repair the three intentional ownership bugs in `starter/core.cp…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets87/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Quick check

Why does moc reject template <typename SampleT> class WaveformView : public QWidget { Q_OBJECT ... };?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets88/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Quick check

An abstract interface class ICanBus { public: ~ICanBus() = default; virtual bool send() = 0; }; is held via std::unique_ptr<ICanBus>. What defect occurs on scope exit?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets89/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Quick check

What compile-time and optimization benefit comes from declaring class AlarmBanner final : public QWidget and marking bool event(QEvent *e) override?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets90/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Lab: lab_m01_cpp20_qobject_raii

  • Production Qt 6 HMIs crash during dialog transitions when an RAII descriptor guard clobbers itself on self-…

Verify: ./check.sh exits 0.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets91/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Summary

  • Declaring any virtual function adds one hidden vptr per instance pointing to a per-class vtable, whereas a C++20 concept constrains templates at compile time with zero indirect-branch overhead.
  • Deleting a derived object through a base-class pointer whose destructor is non-virtual invokes undefined behavior under ISO C++20; polymorphic interfaces must declare virtual ~Interface() = default;.
  • Marking virtual overrides with override catches base-signature drift at compile time, while marking leaf widgets final lets the optimizer devirtualize calls through leaf pointers.
  • Value structs such as fixed-point MilliVolts cleanly overload operator<=> and operator+, whereas Q_OBJECT classes forbid copy/value operators and cannot be C++ class templates because moc emits concrete QMetaObject globals.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets92/570

GL-Q01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Key takeaways

  • Deleting a derived object through a base-class pointer whose destructor is non-virtual invokes undefined behavior under ISO C++20; polymorphic interfaces must declare virtual ~Interface() = default;.
  • Marking virtual overrides with override catches base-signature drift at compile time, while marking leaf widgets final lets the optimizer devirtualize calls through leaf pointers.
  • Value structs such as fixed-point MilliVolts cleanly overload operator<=> and operator+, whereas Q_OBJECT classes forbid copy/value operators and cannot be C++ class templates because moc emits concrete QMetaObject globals.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets93/570

m02/

>_ Kernel Systems Academy

Qt 6 PIMPL ABI, Designer uic Forms & moc Meta-Object Tables

Master Qt 6 module boundaries, d_ptr/q_ptr binary compatibility, UTF-16LE QString and QByteArray atomic Copy-on-Write detach rules, uic setupUi() C++ generation, and moc QMetaObject string tables plus qt_static_metacall void** dispatch.

  1. 2.1 Qt 6 Module Split, d_ptr PIMPL ABI & Implicitly Shared COW Buffers
  2. 2.2 Qt Designer .ui XML, uic setupUi() Generation & Code-First HMIs
  3. 2.3 Inside moc: Q_OBJECT, QMetaObject String Tables & qt_static_metacall

lab → Packed Meta-String Table, void ** Metacall Router & Re-Entrant Disconnect

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets94/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Qt 6 Module Split, d_ptr PIMPL ABI & Implicitly Shared COW Buffers

free preview30 min

What you'll learn

  • Select minimal Qt 6 module dependencies so headless Linux telemetry daemons never link GUI raster or windowing libraries.
  • Implement a binary-compatible d_ptr and q_ptr (Private / Public) facade whose sizeof remains invariant when private fields grow.
  • Eliminate accidental Copy-on-Write heap allocations on QString and QByteArray read paths using std::as_const(), constData(), and QStringView.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets95/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Binary Compatibility and Zero-Copy Value Passing in Qt 6

  • On an embedded root filesystem, linking a background CAN-bus logger against Qt6::Widgets drags `libQt6Wid…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets96/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Binary Compatibility and Zero-Copy Value Passing in Qt 6

  • Across every module, Qt solves two classic C++ library pain points.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets97/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Binary Compatibility and Zero-Copy Value Passing in Qt 6

fig_m02_l01_a.svg

Figure 2.1a: d_ptr freezes sizeof(PublicClass) across Qt 6 minor releases while atomic QArrayData refcounts defer buffer cloning until mutation.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets98/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Mental model

note: Qt's d_ptr and implicit sharing work like a standardized shipping manifest (PublicClass) clipping onto a sealed cargo container (Private / QArrayData): customs scanners always read the exact same manifest card dimensions regardless of what racks change inside the box, and multiple departments share read-only tracking slips until someone breaks the seal to repack.

Where it stops working: Unlike physical shipping containers, QString and QByteArray are NOT thread-safe for concurrent mutation on the same C++ instance: only the internal QArrayData reference counter is atomic (std::memory_order_acq_rel), so two threads sharing distinct copies safely read/detach independently, whereas two threads mutating the SAME QString & variable still race on its 3-word header.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets99/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

PIMPL (d_ptr / q_ptr) and Implicit Sharing (COW)

definition: PIMPL (Pointer to IMPLementation, standardized in Qt as the d-pointer pattern via Q_DECLARE_PRIVATE and Q_DECLARE_PUBLIC) moves all private state of Foo into FooPrivate accessed via d_ptr, while FooPrivate holds Foo *q_ptr to invoke public methods or emit signals on its owner. Implicit sharing (Copy-on-Write) pairs a 24-byte QArrayDataPointer<T> ({ QArrayData *d, T *ptr, qsizetype size } on 64-bit Qt 6) with an atomic reference count so copying QString (UTF-16LE char16_t) or QByteArray (char) is O(1) until mutated.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets100/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Binary Compatibility and Zero-Copy Value Passing in Qt 6

Forward-declare ClassPrivate in the public header and keep only d_ptr inside the public class layout.

d_ptr stabilizes ABI sizeof; std::as_const() and constData() prevent silent COW detaches.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets101/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Inside Qt 6 QArrayDataPointer Layout and UTF-16LE vs Byte Storage

  • Qt 6 modernized QString, QByteArray, and QList<T> around a three-word QArrayDataPointer header (`24…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets102/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Inside Qt 6 QArrayDataPointer Layout and UTF-16LE vs Byte Storage

  • Pay close attention to element encoding!
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets103/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Inside Qt 6 QArrayDataPointer Layout and UTF-16LE vs Byte Storage

fig_m02_l01_b.svg

Figure 2.1b: Qt 6's 3-word QArrayDataPointer decouples control-block ownership (d) from payload start (ptr), powering zero-alloc QStringLiteral.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets104/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

cow_pimpl_codec.cpp

learner@ksa: ~/gl-q01/m02-l01
learner@ksa:~/gl-q01/m02-l01$ bat cow_pimpl_codec.cpp File: cow_pimpl_codec.cpp    #include <QByteArray>    #include <QString>    #include <QtGlobal>    #include <cstdint>    #include <memory>    #include <utility>        namespace hmi {        class FrameCodecPrivate;        class FrameCodec {    public:        explicit FrameCodec(std::uint32_t seed);
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets105/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

QArrayData-PIMPL

QArrayData-PIMPL(3qt) at a glance — GL-Q01
QArrayData-PIMPL(3qt)       GL-Q01 Quick Reference       QArrayData-PIMPL(3qt) NAME       Q_DECLARE_PRIVATE, Q_DECLARE_PUBLIC, QString, QByteArray - Qt 6 ABI &       COW rules SYNOPSIS       Q_DECLARE_PRIVATE(Class)   // defines inline d_func() helper accessing d_ptr       Q_DECLARE_PUBLIC(Class)    // defines inline q_func() helper accessing q_ptr       const char *QByteArray::constData() const noexcept;       const QChar *QString::constData() const noexcept; RULES       1. Define ~PublicClass() out-of-line in .cpp after PublicClassPrivate       is complete. 2. QString stores UTF-16LE (2 bytes per QChar); QByteArray       stores 8-bit bytes. 3. Non-const data(), operator[], and begin() detach       (deep-copy) whenever ref > 1. Use constData(), at(), cbegin(), or       std::as_const() on read-only paths. Kernel Systems Academy              m02-l01              QArrayData-PIMPL(3qt) GL-Q01 quick reference · full manual page: man 3qt QArrayData-PIMPL 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets106/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Proving d_ptr ABI Invariance and Range-For COW Hazards in C++20

  • In verify.cpp, we construct both a bidirectional d_ptr/q_ptr PimplPanel facade and a generic `CowAr…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets107/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Proving d_ptr ABI Invariance and Range-For COW Hazards in C++20

  • Look closely at lines 88-100 in verify.cpp: iterating ByteBuf bad_loop = master; via `for (char c : bad…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets108/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m02-l01
learner@ksa:~/gl-q01/m02-l01$ bat verify.cpp File: verify.cpp    #include <atomic>    #include <cassert>    #include <cstddef>    #include <cstdint>    #include <cstdio>    #include <cstring>    #include <memory>    #include <utility>        static int g_heap_allocs = 0;        template <typename T>    class CowArray {        struct Block {
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets109/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Verifying PIMPL Footprint and COW Allocation Counts

  • Inspect ./verify output: `PIMPL sizeof=8b q_eval=170 allocs_after_const=1 allocs_after_nonconst=2 utf16_b…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets110/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Verifying PIMPL Footprint and COW Allocation Counts

  • Meanwhile, std::as_const(good_loop) kept g_heap_allocs at 1, whereas omitting std::as_const on `bad…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets111/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Verifying PIMPL Footprint and COW Allocation Counts

learner@ksa: ~/gl-q01/m02-l01
learner@ksa:~/gl-q01/m02-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m02-l01./verifyPIMPL sizeof=8b q_eval=170 allocs_after_const=1 allocs_after_nonconst=3 utf16_bytes=6learner@ksa:~/gl-q01/m02-l01
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets112/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Verifying PIMPL Footprint and COW Allocation Counts

strace — learner@ksa: ~/gl-q01/m02-l01
learner@ksa:~/gl-q01/m02-l01strace -e trace=write,exit_group ./verifywrite(1, "PIMPL sizeof=8b q_eval=170 alloc"..., 86) = 86exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets113/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Dangling Views, Incomplete-Type unique_ptr Destructors & False Detaches

  • Mastering d_ptr/q_ptr and implicit sharing explains why Qt 6 APIs pass QString and QByteArray clean…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets114/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Dangling Views, Incomplete-Type unique_ptr Destructors & False Detaches

  • Next, Lesson 2.2 examines how Qt Designer .ui XML forms compile via uic into C++ setupUi() headers an…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets115/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Writing class Codec { ~Codec() {} ... std::unique_ptr<CodecPrivate> d_ptr; }; in codec.hpp fails compilation in client .cpp files with invalid application of 'sizeof' to incomplete type 'CodecPrivate'. - Root Cause: std::default_delete<CodecPrivate>::operator() static-asserts sizeof(CodecPrivate) > 0 at the point where ~Codec() is defined; in codec.hpp, CodecPrivate is only forward-declared! - Fix: Declare ~Codec(); (without = default or {}) in codec.hpp, and place Codec::~Codec() = default; inside codec.cpp below the full definition of CodecPrivate.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets116/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Code obtains const char *hdr = buf.constData();, then calls buf[8] = 0x7E; when buf was shared (ref == 2), and later reads hdr—observing stale or freed memory if the original owner also dropped its reference! - Root Cause: buf[8] = 0x7E triggers detach(), allocating a brand-new QArrayData buffer for buf and decrementing ref on the block hdr still points into. - Fix: Re-acquire constData() / iterators AFTER all mutations finish, or call detach() upfront before taking interior pointers.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets117/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Guided Practice

  • Add move-assignment and an edit_in_place(std::size_t idx, T val) method to CowArray<T> in verify.cpp,…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets118/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Independent Practice

  • Refactor a header-heavy sensor parser class into sensor_parser.hpp and sensor_parser.cpp using `std::un…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets119/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Quick check

An engineer writes QString copy = title; for (QChar ch : copy) { hash ^= ch.unicode(); }. Why does this read-only loop allocate a duplicate UTF-16LE heap buffer?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets120/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Quick check

How do d_ptr (Q_DECLARE_PRIVATE) and q_ptr (Q_DECLARE_PUBLIC) preserve binary compatibility across Qt 6 minor shared-library upgrades?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets121/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Quick check

Why must a headless Linux telemetry service link Qt6::Core instead of Qt6::Widgets in CMake?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets122/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Summary

  • Qt 6 splits QtCore (non-GUI event/meta/IPC), QtGui (windows, fonts, QPainter, RHI), and QtWidgets so headless daemons link Qt6::Core without pulling Wayland or X11 display dependencies.
  • Public Qt classes keep sizeof(PublicClass) constant across minor library upgrades by storing internal fields in a *Private heap struct accessed via d_ptr (Q_DECLARE_PRIVATE) with back-pointer q_ptr (Q_DECLARE_PUBLIC).
  • QString (UTF-16LE char16_t units) and QByteArray (raw bytes) share one atomically reference-counted QArrayData block across copies until a mutating call triggers detach() when ref > 1.
  • Iterating a shared non-const QString or QByteArray with for (auto ch : buf) invokes non-const begin() and forces an unnecessary deep heap copy unless wrapped in std::as_const(buf) or read via constData().
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets123/570

GL-Q01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Key takeaways

  • Public Qt classes keep sizeof(PublicClass) constant across minor library upgrades by storing internal fields in a *Private heap struct accessed via d_ptr (Q_DECLARE_PRIVATE) with back-pointer q_ptr (Q_DECLARE_PUBLIC).
  • QString (UTF-16LE char16_t units) and QByteArray (raw bytes) share one atomically reference-counted QArrayData block across copies until a mutating call triggers detach() when ref > 1.
  • Iterating a shared non-const QString or QByteArray with for (auto ch : buf) invokes non-const begin() and forces an unnecessary deep heap copy unless wrapped in std::as_const(buf) or read via constData().
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets124/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Qt Designer .ui XML, uic setupUi() Generation & Code-First HMIs

free preview25 min

What you'll learn

  • Dissect every statement emitted by uic inside Ui_Panel::setupUi(QWidget *) and retranslateUi(QWidget *).
  • Eliminate silent field regressions from on_<objectName>_<signal> slots by enforcing explicit pointer-to-member QObject::connect wiring.
  • Architect clean private Ui::Panel wrappers and parameterized code-first channel strips with stable objectName test hooks.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets125/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

What Actually Happens to a Designer .ui File During Compilation

  • Engineers transitioning from web DOMs or QtQuick .qml scenes often assume a Qt Designer panel.ui XML…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets126/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

What Actually Happens to a Designer .ui File During Compilation

  • At the very last line of setupUi(root), however, uic emits QMetaObject::connectSlotsByName(root).
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets127/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

What Actually Happens to a Designer .ui File During Compilation

fig_m02_l02_a.svg

Figure 2.2a: uic emits ordinary C++ widget allocations in ui_*.h, making explicit PMF connect compile-time safe on widget renames.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets128/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Mental model

note: A Designer .ui file compiled by uic acts like a sheet-metal DXF drawing converted into hard-coded G-code toolpaths before shipping to the mill: the shop controller executes native axis moves directly without carrying a CAD file reader.

Where it stops working: Generated ui_*.h files are monolithic imperative scripts, so editing one margin in Qt Designer frequently reflows 80 lines of XML attributes in git diff, whereas a 15-line code-first C++ loop instantiating 8 identical sensor channel rows yields surgical, reviewable diffs.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets129/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

uic (User Interface Compiler) and Ui::Form Namespace

definition: uic (User Interface Compiler) is Qt's build-time C++ code generator for QtWidgets XML forms (.ui). For <class>PumpPanel</class>, uic emits class Ui_PumpPanel holding raw child widget pointers (QLabel *ch0Temp;), setupUi(QWidget *) to construct and parent those children onto the host widget, retranslateUi(QWidget *) wrapping strings in QCoreApplication::translate(), and an empty subclass namespace Ui { class PumpPanel : public Ui_PumpPanel {}; } so headers can forward-declare namespace Ui { class PumpPanel; }!

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets130/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

What Actually Happens to a Designer .ui File During Compilation

Forward-declare Ui::PumpPanel in pump_panel.hpp and hold std::unique_ptr<Ui::PumpPanel> m_ui privately.

Hold Ui::Form privately via unique_ptr, ban connectSlotsByName, and loop repetitive channels in C++.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets131/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Anatomy of Generated ui_*.h Code and Hybrid Form Composition

  • Notice a subtle ownership detail when PumpPanel holds std::unique_ptr<Ui::PumpPanel> m_ui in `panel_uic…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets132/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Anatomy of Generated ui_*.h Code and Hybrid Form Composition

  • Observe also how retranslateUi(this) works during live operator language switching (e.g., English to Germ…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets133/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Anatomy of Generated ui_*.h Code and Hybrid Form Composition

fig_m02_l02_b.svg

Figure 2.2b: Ui_PumpPanel is a non-QObject struct of observer pointers; the host QWidget passed to setupUi(this) owns every child control.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets134/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

panel_uic_vs_code.cpp

learner@ksa: ~/gl-q01/m02-l02
learner@ksa:~/gl-q01/m02-l02$ bat panel_uic_vs_code.cpp File: panel_uic_vs_code.cpp    #include <QCoreApplication>    #include <QEvent>    #include <QHBoxLayout>    #include <QLabel>    #include <QPushButton>    #include <QWidget>    #include <array>    #include <memory>        // Exact structure emitted by uic into ui_pump_panel.h:    class Ui_PumpPanel {    public:        QHBoxLayout *rootRow = nullptr;        QPushButton *haltDriveBtn = nullptr;
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets135/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

uic

uic(1) at a glance — GL-Q01
uic(1)                      GL-Q01 Quick Reference                      uic(1) NAME       uic - Qt User Interface Compiler lowering .ui XML into C++ setupUi()       headers SYNOPSIS       uic [options] <form>.ui -o ui_<form>.h // Triggered automatically via       set_target_properties(tgt PROPERTIES AUTOUIC ON) GENERATED SYMBOLS       class Ui_<Form> { void setupUi(QWidget *host); void       retranslateUi(QWidget *host); }; namespace Ui { class <Form> : public       Ui_<Form> {}; } Kernel Systems Academy                     m02-l02                      uic(1) GL-Q01 quick reference · full manual page: man 1 uic 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets136/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Simulating uic setupUi(), Retranslation & Rename Hazards in C++20

  • In verify.cpp, we model Ui_PumpPanel::setup_ui() and retranslate_ui() in pure ISO C++20, populating a…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets137/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Simulating uic setupUi(), Retranslation & Rename Hazards in C++20

  • Watch what happens when eStopBtn is renamed to haltDriveBtn in the form descriptor: `connect_slots_by_n…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets138/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m02-l02
learner@ksa:~/gl-q01/m02-l02$ bat verify.cpp File: verify.cpp    #include <array>    #include <cassert>    #include <cstdio>    #include <memory>    #include <string>    #include <string_view>    #include <vector>        struct SimWidget {        std::string class_name;        std::string object_name;        std::string text;        std::vector<std::unique_ptr<SimWidget>> children;
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets139/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Confirming Zero-Realloc Retranslation and Auto-Connect Breakage

  • Confirm ./verify outputs uic children=5 de_text='Antrieb Stopp' auto_connect_after_rename=0.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets140/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Confirming Zero-Realloc Retranslation and Auto-Connect Breakage

  • Equally clear, auto_connect_after_rename=0 proves why on_<objectName>_<signal> is banned in industrial…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets141/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Confirming Zero-Realloc Retranslation and Auto-Connect Breakage

learner@ksa: ~/gl-q01/m02-l02
learner@ksa:~/gl-q01/m02-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m02-l02./verifyuic children=5 de_text='Antrieb Stopp' auto_connect_after_rename=0learner@ksa:~/gl-q01/m02-l02
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets142/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Confirming Zero-Realloc Retranslation and Auto-Connect Breakage

strace — learner@ksa: ~/gl-q01/m02-l02
learner@ksa:~/gl-q01/m02-l02strace -e trace=write,exit_group ./verifywrite(1, "uic children=5 de_text='Antrieb "..., 67) = 67exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets143/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Designer Form Inheritance, Missing LanguageChange & Layout Pitfalls

  • You now see .ui files for what they truly are: an optional ahead-of-time C++ widget-tree macro lowered by…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets144/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Designer Form Inheritance, Missing LanguageChange & Layout Pitfalls

  • Next, Lesson 2.3 opens Qt's deepest black box: how moc compiles Q_OBJECT into packed string tables, rel…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets145/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: External controller code writes panel->haltDriveBtn->setEnabled(false); directly, scattering internal widget state mutations across 15 unrelated .cpp files. - Root Cause: Inheriting public Ui::Panel exposes every generated raw child pointer in Ui_Panel as part of Panel's public C++ API, destroying encapsulation. - Fix: Store std::unique_ptr<Ui::Panel> m_ui; (or Ui::Panel m_ui; inside .cpp-only classes) under private: and expose semantic controller methods (setDriveArmed(bool)) and signals (emergencyHaltRequested()).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets146/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: A .ui panel looks aligned at 800x480 in Designer, then clips half its buttons at 1024x600 or 1280x800 DPI scaling on target hardware. - Root Cause: Dropping widgets onto a Designer canvas without applying a top-level QVBoxLayout/QGridLayout makes uic emit hardcoded setGeometry(QRect(x, y, w, h)) pixel coordinates! - Fix: Always assign a top-level layout on the form root in Designer (verify no red 'broken layout' icon appears in the Object Inspector) so uic emits QLayout::addWidget rules.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets147/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Guided Practice

  • Extend UiPumpPanel in verify.cpp to store per-channel engineering unit strings updated inside `retransl…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets148/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Independent Practice

  • Write a pure C++20 code-first layout specification for an 8-channel ThermocoupleMatrixWidget (2 rows x 4…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets149/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Quick check

Which runtime file from status_panel.ui must be installed onto the embedded ARMv7-A root filesystem when built via CMAKE_AUTOUIC?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets150/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Quick check

Why do safety-conscious Qt 6 teams forbid void on_ackBtn_clicked() slots in favor of connect(m_ui->ackBtn, &QPushButton::clicked, this, &Panel::acknowledge)?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets151/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Quick check

When PumpPanelWidget holds std::unique_ptr<Ui::PumpPanel> m_ui; and calls m_ui->setupUi(this), what deletes the child QPushButton *haltDriveBtn created inside setupUi?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets152/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Summary

  • During a CMAKE_AUTOUIC build, uic compiles panel.ui XML ahead-of-time into ui_panel.h containing Ui_Panel::setupUi() and retranslateUi(), shipping zero XML files or XML parsers to the target.
  • Composing std::unique_ptr<Ui::Panel> m_ui as a private member encapsulates generated child widget pointers, whereas public Ui::Panel inheritance leaks internal controls to external callers.
  • QMetaObject::connectSlotsByName matches on_<objectName>_<signal> slot names via runtime string lookup, so renaming a widget in Designer silently breaks button wiring with zero C++ compiler errors.
  • Code-first C++ widget construction excels for parameterized multi-channel industrial HMIs, producing compact Git diffs, loops over channel arrays, and compile-time verified PMF QObject::connect calls.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets153/570

GL-Q01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Key takeaways

  • Composing std::unique_ptr<Ui::Panel> m_ui as a private member encapsulates generated child widget pointers, whereas public Ui::Panel inheritance leaks internal controls to external callers.
  • QMetaObject::connectSlotsByName matches on_<objectName>_<signal> slot names via runtime string lookup, so renaming a widget in Designer silently breaks button wiring with zero C++ compiler errors.
  • Code-first C++ widget construction excels for parameterized multi-channel industrial HMIs, producing compact Git diffs, loops over channel arrays, and compile-time verified PMF QObject::connect calls.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets154/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Inside moc: Q_OBJECT, QMetaObject String Tables & qt_static_metacall

free preview35 minlab lab_m02_moc_signal_dispatch

What you'll learn

  • Expand Q_OBJECT, signals:, slots:, and emit to the exact C++20 declarations compiled by g++.
  • Trace void *_a[] layout (_a[0] return pointer + _a[1..N] stack argument pointers) from signal call site through QMetaObject::activate into qt_static_metacall.
  • Calculate global-to-local method index subtraction across multi-level QObject inheritance hierarchies.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets155/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Zero Compiler Magic: How Signals Become Ordinary C++ Function Calls

  • Newcomers to Qt often treat signals:, slots:, and emit like magical language extensions hidden inside…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets156/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Zero Compiler Magic: How Signals Become Ordinary C++ Function Calls

  • Where does the body of PressureSensor::readingUpdated come from if you only wrote its prototype in `press…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets157/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Zero Compiler Magic: How Signals Become Ordinary C++ Function Calls

fig_m02_l03_a.svg

Figure 2.3a: Same-thread DirectConnection signal emission allocates zero heap bytes: receivers read arguments directly off the sender's stack via void *_a[].

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets158/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Mental model

note: moc acts like an in-process RPC stub generator: you write clean C++ function prototypes under signals:, and moc writes the marshaling stub that bundles local stack variable addresses into an indexed void *_a[] envelope and hands it to the QMetaObject::activate switchboard.

Where it stops working: Unlike network RPC stubs that serialize bytes onto a wire, same-thread Qt::DirectConnection passes raw stack addresses (&_t1, &_t2) in _a[]; only when QMetaObject::activate crosses a thread boundary (Qt::QueuedConnection) does Qt allocate a QMetaCallEvent and copy-construct each parameter via QMetaType.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets159/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

QMetaObject, qt_meta_stringdata, and qt_static_metacall

definition: QMetaObject is a constexpr/.rodata descriptor emitted once per Q_OBJECT class linking to superdata (&Base::staticMetaObject), qt_meta_stringdata (a single contiguous character buffer indexed by { uint32_t offset, uint32_t len } pairs in Qt 6), qt_meta_data (method flags, arity, and QMetaType arrays), and qt_static_metacall(QObject *, Call, int _id, void **_a), a static function pointer dispatching local method IDs without virtual-table growth per slot.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets160/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Zero Compiler Magic: How Signals Become Ordinary C++ Function Calls

Inspect how Q_OBJECT declares staticMetaObject, two virtual hooks, and one static dispatcher.

Signals pack {nullptr, &arg1..&argN} into void *_a[] and dispatch via base-subtracted metacall IDs.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets161/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Dissecting moc_*.cpp Byte-for-Byte: String Tables, _a[] & Inheritance

  • Why did Qt introduce qt_static_metacall instead of making every single slot a C++ virtual function?
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets162/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Dissecting moc_*.cpp Byte-for-Byte: String Tables, _a[] & Inheritance

  • Examine pressure_meta.hpp below, which pairs a Qt 6.8 PressureSensor class with the exact annotated C++…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets163/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Dissecting moc_*.cpp Byte-for-Byte: String Tables, _a[] & Inheritance

fig_m02_l03_b.svg

Figure 2.3b: Base-class offset subtraction lets moc generate Derived's switch(0..K-1) without knowing future changes to QObject's method count.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets164/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

pressure_meta.hpp

learner@ksa: ~/gl-q01/m02-l03
learner@ksa:~/gl-q01/m02-l03$ bat pressure_meta.hpp File: pressure_meta.hpp    #pragma once    #include <QObject>    #include <cstdint>        namespace hmi {        class PressureSensor : public QObject {        Q_OBJECT    public:        explicit PressureSensor(QObject *parent = nullptr) : QObject(parent) {}            void ingestSample(std::int32_t kPa, std::uint32_t faultMask) {            if (kPa != m_lastKpa || faultMask != m_lastMask) {                m_lastKpa = kPa;
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets165/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

moc

moc(1) at a glance — GL-Q01
moc(1)                      GL-Q01 Quick Reference                      moc(1) NAME       moc, QMetaObject::activate, qt_static_metacall - Qt 6 meta-object       dispatch SYNOPSIS       moc [options] <header>.hpp -o moc_<header>.cpp       static void QMetaObject::activate(QObject *sender, const QMetaObject *m,                                      int local_signal_index, void **argv);        CALLING CONVENTION (void **argv) argv[0] Pointer to return value       storage, or nullptr when ignored / void. argv[1] Address of parameter 1       (const void * cast to void *). argv[k] Address of parameter k. INHERITANCE INDEXING Kernel Systems Academy                     m02-l03                      moc(1) GL-Q01 quick reference · full manual page: man 1 moc 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets166/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Constructing a Packed String-Table and void** Meta-Object Engine in C++20

  • In verify.cpp, we build a faithful C++20 miniature of moc's generated tables: a constexpr `MetaString…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets167/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Constructing a Packed String-Table and void** Meta-Object Engine in C++20

  • Verify every step of main(): string_at(1) slices "readingUpdated" without heap allocation, emitting `…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets168/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m02-l03
learner@ksa:~/gl-q01/m02-l03$ bat verify.cpp File: verify.cpp    #include <array>    #include <cassert>    #include <cstdint>    #include <cstdio>    #include <memory>    #include <string_view>    #include <vector>        namespace hmi {        struct OffsetLen {        std::uint32_t offset;        std::uint32_t len;    };
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets169/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Verifying String Table Slicing and void** Metacall Return Values

  • Confirm ./verify prints moc sig='readingUpdated' rx_kpa=245 mask=0x4 ret=3100 base_reset=1.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets170/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Verifying String Table Slicing and void** Metacall Return Values

  • Next time you inspect an embedded crash dump in gdb and see QMetaObject::activate -> `qt_static_metacal…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets171/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Verifying String Table Slicing and void** Metacall Return Values

learner@ksa: ~/gl-q01/m02-l03
learner@ksa:~/gl-q01/m02-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m02-l03./verifymoc sig='readingUpdated' rx_kpa=310 mask=0x0 ret=3100 base_reset=1learner@ksa:~/gl-q01/m02-l03
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets172/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Verifying String Table Slicing and void** Metacall Return Values

strace — learner@ksa: ~/gl-q01/m02-l03
learner@ksa:~/gl-q01/m02-l03strace -e trace=write,exit_group ./verifywrite(1, "moc sig='readingUpdated' rx_kpa="..., 67) = 67exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets173/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Custom QMetaType Registration & Hand-Written Signal Pitfalls

  • Module 2 has demystified Qt 6's binary and compile-time machinery: d_ptr/q_ptr ABI insulation, atomic C…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets174/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Custom QMetaType Registration & Hand-Written Signal Pitfalls

  • Proceed to the lab_m02_moc_signal_dispatch studio below to repair a multi-slot MetaEndpoint router supp…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets175/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Linker aborts with multiple definition of 'hmi::PressureSensor::readingUpdated(int, unsigned int)' between pressure_meta.cpp.o and mocs_compilation.cpp.o. - Root Cause: moc ALWAYS emits the C++ function body for every prototype listed under signals:; providing a second body in your .cpp file violates the C++ One Definition Rule (ODR). - Fix: Leave signals: entries strictly as declarations in your .hpp file and let moc generate their QMetaObject::activate bodies.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets176/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: A signal carrying const CanPayload & works on same-thread DirectConnection, then silently fails at runtime with QObject::connect: Cannot queue arguments of type 'CanPayload' when moved to a worker QThread. - Root Cause: Same-thread DirectConnection only forwards &payload in _a[1], whereas QueuedConnection must heap-clone CanPayload via QMetaType after the sender returns! - Fix: Ensure custom payload structs are default/copy-constructible value types and declare Q_DECLARE_METATYPE(CanPayload) (plus qRegisterMetaType<CanPayload>() if matched by string name).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets177/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Guided Practice

  • Add a third inheritance level CalibratedSensor : public DerivedSensor to verify.cpp with `method_offset…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets178/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Independent Practice

  • Open labs/lab_m02_moc_signal_dispatch/ and repair all three defects in starter/core.cpp—off-by-one `_a[…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets179/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Quick check

What does _a[0] hold inside the void *_a[] array passed to qt_static_metacall during QMetaObject::InvokeMetaMethod?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets180/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Quick check

What do emit and signals expand to when g++ preprocesses a Qt 6.8 header?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets181/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Quick check

Why does Derived::qt_metacall start with _id = Base::qt_metacall(_c, _id, _a);?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets182/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Lab: lab_m02_moc_signal_dispatch

  • Debugging subtle Qt 6 signal bugs—nested QSignalBlocker scopes prematurely unblocking an editor, custom `…

Verify: ./check.sh exits 0.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets183/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Summary

  • In <qtmetamacros.h>, emit expands to nothing, slots expands to nothing, and signals expands to public so callers can pass &Sender::signalName into PMF QObject::connect.
  • Emitting a Q_OBJECT signal invokes a moc-generated C++ member function that packs operand addresses into void *_a[] (_a[0] return storage, _a[1..N] argument addresses) and calls QMetaObject::activate.
  • moc packs class, signal, slot, and parameter names into one contiguous .rodata qt_meta_stringdata offset/length table alongside qt_meta_data integer method descriptors, requiring zero startup heap allocations.
  • qt_metacall delegates to SuperClass::qt_metacall first, subtracting each base class's method count from _id so qt_static_metacall switches on a zero-based local method index.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets184/570

GL-Q01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Key takeaways

  • Emitting a Q_OBJECT signal invokes a moc-generated C++ member function that packs operand addresses into void *_a[] (_a[0] return storage, _a[1..N] argument addresses) and calls QMetaObject::activate.
  • moc packs class, signal, slot, and parameter names into one contiguous .rodata qt_meta_stringdata offset/length table alongside qt_meta_data integer method descriptors, requiring zero startup heap allocations.
  • qt_metacall delegates to SuperClass::qt_metacall first, subtracting each base class's method count from _id so qt_static_metacall switches on a zero-based local method index.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets185/570

m03/

>_ Kernel Systems Academy

PMF Signal Lifetimes, Event Filters & Monotonic Timers

Eliminate dangling lambda slot crashes with 4-argument context-bound PMF connections, master synchronous sendEvent versus heap-queued postEvent compression and LIFO eventFilter interception, and schedule drift-free CLOCK_MONOTONIC timers without starving QPaintEvent.

  1. 3.1 Pointer-to-Member QObject::connect, Context Lifetimes & Lambda Hazards
  2. 3.2 Event Loops, postEvent vs sendEvent & QObject::eventFilter
  3. 3.3 Monotonic QTimer, Precise vs Coarse Coalescing & GUI Frame Stalls

lab → Cooperative Reactor Loop: Priority Events, LIFO Filters & Monotonic Timers

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets186/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Pointer-to-Member QObject::connect, Context Lifetimes & Lambda Hazards

free preview30 min

What you'll learn

  • Eliminate use-after-free and wrong-thread races in [this]-capturing lambdas by supplying the 4-argument receiver context QObject *.
  • Wire overloaded and prefix-argument member slots cleanly using qOverload<...>() and PMF QObject::connect.
  • Prevent duplicate slot invocations across repeated state transitions using Qt::UniqueConnection and QMetaObject::Connection handles.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets187/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

The Number-One Use-After-Free Crash in Modern C++20 Qt 6 Codebases

  • Qt 4's string-based connect(src, SIGNAL(fault(int)), dst, SLOT(showFault(int))) deferred signature checki…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets188/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

The Number-One Use-After-Free Crash in Modern C++20 Qt 6 Codebases

  • Yet C++20 lambdas introduced a subtle, devastating trap: the 3-argument overload `connect(bus, &Bus::fault,…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets189/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

The Number-One Use-After-Free Crash in Modern C++20 Qt 6 Codebases

fig_m03_l01_a.svg

Figure 3.1a: Every lambda capturing widget state MUST pass a context QObject* as the 3rd argument to QObject::connect.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets190/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Mental model

note: A 3-argument lambda connect is like clipping a high-voltage test lead onto a removable PCB card without routing through the card-edge interlock connector: pull the card out of the chassis and the live lead arcs straight into an empty slot.

Where it stops working: Passing this as the 3rd context argument only protects this! If your lambda captures a SECOND independent raw pointer [this, otherDialog] and otherDialog dies while this stays alive, otherDialog will still dangle unless guarded with QPointer<QDialog>.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets191/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Context QObject, Qt::AutoConnection, and Qt::UniqueConnection

definition: In Qt 6's 4-argument functor overload QObject::connect(sender, &S::sig, context, functor, type), context is a const QObject * supplying two runtime properties: destruction lifetime (~QObject() on context destroys the functor QSlotObjectBase immediately) and thread affinity (Qt::AutoConnection compares QThread::currentThread() with context->thread(), posting a QMetaCallEvent when they differ). Qt::UniqueConnection (0x80) compares PMF QSlotObject addresses so re-running setup code never registers duplicate PMF connections.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets192/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

The Number-One Use-After-Free Crash in Modern C++20 Qt 6 Codebases

Use 4-argument PMF connect directly whenever a member slot matches or accepts a prefix of signal args.

Always pass a 3rd-arg context QObject* for lambdas; use Qt::UniqueConnection on PMFs.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets193/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Inside QSlotObjectBase, Prefix Arity Dropping & UniqueConnection

  • How does Qt 6 invoke a C++20 lambda or member pointer without moc knowing the lambda's signature?
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets194/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Inside QSlotObjectBase, Prefix Arity Dropping & UniqueConnection

  • Now understand why Qt::UniqueConnection works on &DiagnosticPopup::refreshBadge in `pmf_lifetime_panel.…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets195/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Inside QSlotObjectBase, Prefix Arity Dropping & UniqueConnection

fig_m03_l01_b.svg

Figure 3.1b: Dual-linked Connection nodes let either ~Sender() or ~Context() sever a slot in O(1) list manipulation.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets196/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

pmf_lifetime_panel.cpp

learner@ksa: ~/gl-q01/m03-l01
learner@ksa:~/gl-q01/m03-l01$ bat pmf_lifetime_panel.cpp File: pmf_lifetime_panel.cpp    #include <QLabel>    #include <QMetaObject>    #include <QObject>    #include <QString>    #include <QWidget>        namespace hmi {        class TelemetryBus : public QObject {        Q_OBJECT    public:        explicit TelemetryBus(QObject *parent = nullptr) : QObject(parent) {}    signals:        void faultRaised(int code, const QString &subsystem);
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets197/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

QObject-connect

QObject-connect(3qt) at a glance — GL-Q01
QObject-connect(3qt)        GL-Q01 Quick Reference        QObject-connect(3qt) NAME       QObject::connect, QObject::disconnect, qOverload - PMF & functor       lifetime rules SYNOPSIS       QMetaObject::Connection QObject::connect(        const QObject *sender, PointerToMemberFunction signal,        const QObject *context, Functor functor,        Qt::ConnectionType type = Qt::AutoConnection);        LIFETIME & THREADING RULES 1. Always supply 'context' when 'functor'       captures widget/object pointers: - Destroying 'context' disconnects the       slot automatically. - Qt::AutoConnection queues onto context->thread()       when emitted cross-thread. 2. Qt::UniqueConnection deduplicates       identical PMF pairs; for lambdas, store Kernel Systems Academy              m03-l01               QObject-connect(3qt) GL-Q01 quick reference · full manual page: man 3qt QObject-connect 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets198/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Verifying Context Auto-Prune, UniqueConnection & 3-Arg Hazards in C++20

  • In verify.cpp, we implement a C++20 Signal<Args...> dispatcher tracking ContextObject `std::weak_ptr<…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets199/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Verifying Context Auto-Prune, UniqueConnection & 3-Arg Hazards in C++20

  • Follow the assertions in main(): calling connect_pmf twice with unique = true registers only one slot…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets200/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m03-l01
learner@ksa:~/gl-q01/m03-l01$ bat verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cstdio>    #include <functional>    #include <memory>    #include <vector>        namespace hmi {        class ContextObject {    public:        ContextObject() : m_alive(std::make_shared<bool>(true)) {}        virtual ~ContextObject() { *m_alive = false; }        ContextObject(const ContextObject &) = delete;
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets201/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Confirming UniqueConnection Deduplication and Context Pruning

  • Verify ./verify prints PMF unique_dup=0 ctx_sum=35 one_shot=1 pruned=0 uaf_3arg=1.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets202/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Confirming UniqueConnection Deduplication and Context Pruning

  • Make this a zero-exception team lint rule: grep every connect( call in pull requests and require a 4th ar…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets203/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Confirming UniqueConnection Deduplication and Context Pruning

learner@ksa: ~/gl-q01/m03-l01
learner@ksa:~/gl-q01/m03-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m03-l01./verifyPMF unique_dup=0 ctx_sum=35 one_shot=1 pruned=1 uaf_3arg=1learner@ksa:~/gl-q01/m03-l01
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets204/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Confirming UniqueConnection Deduplication and Context Pruning

strace — learner@ksa: ~/gl-q01/m03-l01
learner@ksa:~/gl-q01/m03-l01strace -e trace=write,exit_group ./verifywrite(1, "PMF unique_dup=0 ctx_sum=35 one_"..., 59) = 59exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets205/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Qt::UniqueConnection on Lambdas & Multi-Pointer Capture Traps

  • With 4-argument context-bound QObject::connect and Qt::UniqueConnection in your toolkit, signal connect…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets206/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Qt::UniqueConnection on Lambdas & Multi-Pointer Capture Traps

  • Next, Lesson 3.2 traces what happens underneath queued connections and user input: how `QCoreApplication::e…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets207/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: In Qt 6, passing Qt::UniqueConnection to a lambda connect(src, &S::sig, this, [this]{...}, Qt::UniqueConnection) fails compilation (static_assert in Qt 6.8 or returns invalid connection) instead of deduplicating. - Root Cause: Each C++ lambda closure type is unique and lacks a comparable member-function pointer address, so Qt cannot test whether two functor objects represent the 'same' slot. - Fix: Promote the lambda body to a private member function (&MyWidget::updateStatus) when using Qt::UniqueConnection, or store QMetaObject::Connection and disconnect the prior handle before reconnecting.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets208/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Writing int threshold = 80; connect(timer, &QTimer::timeout, this, [&] { check(threshold); }); inside a constructor crashes or reads garbage when timeout fires 50 ms later! - Root Cause: Constructor stack local threshold dies as soon as the constructor returns, leaving [&] holding a dangling stack reference even though this is still alive! - Fix: Never use default by-reference capture [&] in signal lambdas! List explicit value/pointer captures ([this, threshold]) so stack scalars are copied into the closure.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets209/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Guided Practice

  • Extend Signal in verify.cpp to support prefix-argument binding (`Signal<int, int>::connect_0arg(ctx, fn…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets210/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Independent Practice

  • Audit a multi-dialog HMI workflow where a temporary CalibrationWizard connects to a singleton `SensorMana…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets211/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Quick check

A background worker QThread emits reader->packetReady(buf) connected via 3-argument connect(reader, &Reader::packetReady, [label] (const QByteArray &b) { label->setText(...); }). On which thread does label->setText(...) execute?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets212/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Quick check

Why does connect(bus, &TelemetryBus::faultRaised, this, qOverload<>(&QWidget::update)) compile cleanly even though faultRaised(int, const QString &) emits two arguments and update() accepts zero?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets213/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Quick check

When bindBus(bus) may be called multiple times during runtime profile reloads, how does Qt::UniqueConnection behave on connect(bus, &Bus::fault, this, &Panel::onFault, Qt::UniqueConnection)?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets214/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Summary

  • Three-argument QObject::connect(sender, &S::sig, lambda) binds connection lifetime solely to sender, causing a fatal use-after-free crash if lambda captures [this] on a shorter-lived receiver QWidget.
  • Four-argument QObject::connect(sender, &S::sig, receiver, lambda) ties the connection to both endpoints so ~QObject() on receiver disconnects the closure automatically and Qt::AutoConnection queues onto receiver's thread.
  • Pointer-to-member QObject::connect verifies parameter conversions at compile time via QtPrivate::FunctionPointer traits and permits slots to accept a shorter prefix of the signal's arguments.
  • Passing Qt::UniqueConnection bitwise-ORed into connection flags deduplicates identical (sender, &S::sig, receiver, &R::slot) PMF pairs, whereas anonymous C++ lambdas have distinct closure types and require explicit handle tracking.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets215/570

GL-Q01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Key takeaways

  • Four-argument QObject::connect(sender, &S::sig, receiver, lambda) ties the connection to both endpoints so ~QObject() on receiver disconnects the closure automatically and Qt::AutoConnection queues onto receiver's thread.
  • Pointer-to-member QObject::connect verifies parameter conversions at compile time via QtPrivate::FunctionPointer traits and permits slots to accept a shorter prefix of the signal's arguments.
  • Passing Qt::UniqueConnection bitwise-ORed into connection flags deduplicates identical (sender, &S::sig, receiver, &R::slot) PMF pairs, whereas anonymous C++ lambdas have distinct closure types and require explicit handle tracking.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets216/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Event Loops, postEvent vs sendEvent & QObject::eventFilter

free preview30 min

What you'll learn

  • Enforce strict stack allocation for synchronous sendEvent calls and new heap transfer for asynchronous postEvent calls.
  • Implement a central LIFO QObject::eventFilter safety interlock that consumes prohibited operator input (return true) while forwarding benign events (return false).
  • Contrast QWidget::update() posted repaint coalescing against synchronous QWidget::repaint() CPU thrashing.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets217/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Inside QCoreApplication::exec(): Multiplexing, Ownership & Interception

  • When main() enters app.exec(), Qt's thread-local QEventDispatcherUNIX (or Glib) sleeps inside `ppol…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets218/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Inside QCoreApplication::exec(): Multiplexing, Ownership & Interception

  • Before notify() ever calls receiver->event(ev), it walks every watcher attached via `receiver->installE…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets219/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Inside QCoreApplication::exec(): Multiplexing, Ownership & Interception

fig_m03_l02_a.svg

Figure 3.2a: postEvent takes heap ownership and compresses repaints; sendEvent borrows stack events synchronously; LIFO filters consume on true.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets220/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Mental model

note: sendEvent works like handing a reusable laminated checklist directly to a technician and taking it back as soon as they initial it; postEvent drops a single-use paper work order into a pneumatic tube inbox that the dispatch desk owns, merges duplicate repaint slips, and feeds straight into a shredder (delete) once completed.

Where it stops working: An eventFilter watcher MUST live on the same thread as the watched QObject: Qt asserts and refuses cross-thread installEventFilter calls because notify() invokes watcher->eventFilter() synchronously without locking across threads.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets221/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

QCoreApplication::postEvent, sendEvent, and eventFilter

definition: QCoreApplication::sendEvent(QObject *receiver, QEvent *event) is a synchronous thin wrapper around notify() that borrows caller-owned (typically stack) *event and returns bool. QCoreApplication::postEvent(QObject *receiver, QEvent *event, int priority) is thread-safe, takes immediate ownership of heap-allocated event, inserts it by descending priority (High=1, Normal=0, Low=-1 for UpdateRequest), and deletes event after dispatch. QObject::eventFilter intercepts every event addressed to watched in LIFO registration order prior to watched->event().

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets222/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Inside QCoreApplication::exec(): Multiplexing, Ownership & Interception

Use new QEvent exclusively for postEvent and stack QEvent variables for synchronous sendEvent.

Heap-allocate for postEvent, stack-allocate for sendEvent, and end eventFilter with false.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets223/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Priority Queue Ordering, Repaint Compression & LIFO Filter Mechanics

  • Look inside safety_event_filter.cpp below.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets224/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Priority Queue Ordering, Repaint Compression & LIFO Filter Mechanics

  • Examine schedulePanelRefresh and injectSyncSelfTest below the class as well.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets225/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Priority Queue Ordering, Repaint Compression & LIFO Filter Mechanics

fig_m03_l02_b.svg

Figure 3.2b: Scheduling UpdateRequest at LowEventPriority (-1) guarantees all pending data mutations settle before a single paintEvent runs.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets226/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

safety_event_filter.cpp

learner@ksa: ~/gl-q01/m03-l02
learner@ksa:~/gl-q01/m03-l02$ bat safety_event_filter.cpp File: safety_event_filter.cpp    #include <QCoreApplication>    #include <QEvent>    #include <QKeyEvent>    #include <QObject>    #include <QWidget>        namespace hmi {        class JogInterlockFilter final : public QObject {        Q_OBJECT    public:        explicit JogInterlockFilter(QObject *parent = nullptr) : QObject(parent) {}            void setGuardClosed(bool closed) noexcept { m_guardClosed = closed; }
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets227/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

QCoreApplication-events

QCoreApplication-events(3qt) at a glance — GL-Q01
QCoreApplication-events(3qt) GL-Q01 Quick Reference QCoreApplication-events(3qt) NAME       sendEvent, postEvent, installEventFilter - Qt 6 event delivery &       interception SYNOPSIS       static bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event);       static void QCoreApplication::postEvent(QObject *receiver, QEvent *event,                                            int priority = Qt::NormalEventPriority);       void QObject::installEventFilter(QObject *filterObj);       virtual bool QObject::eventFilter(QObject *watched, QEvent *event); CONTRACT       - sendEvent: synchronous; caller owns *event (allocate on stack). -       postEvent: asynchronous & thread-safe; queue owns *event (allocate via       new). - eventFilter: runs in LIFO installation order; true consumes,       false forwards. Kernel Systems Academy          m03-l02           QCoreApplication-events(3qt) GL-Q01 quick reference · full manual page: man 3qt QCoreApplication-events 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets228/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Verifying Priority Draining, Paint Compression & LIFO Filters in C++20

  • In verify.cpp, we build a deterministic C++20 EventDispatcher modeling priority-sorted `post_event(std:…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets229/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Verifying Priority Draining, Paint Compression & LIFO Filters in C++20

  • Inspect main(): audit is installed first and door is installed second (LIFO).
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets230/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m03-l02
learner@ksa:~/gl-q01/m03-l02$ bat verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cstdio>    #include <memory>    #include <vector>        namespace hmi {        enum class EvType { KeyPress, UpdateRequest };        struct Ev {        EvType type;        int key = 0;    };
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets231/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Confirming LIFO Interception and Repaint Coalescing

  • Verify ./verify prints Events blocked=1 audit=1 keys=2 paints=1 drained=2.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets232/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Confirming LIFO Interception and Repaint Coalescing

  • Notice how encoding post_event's parameter as std::unique_ptr<Ev> in C++20 makes passing a stack addres…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets233/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Confirming LIFO Interception and Repaint Coalescing

learner@ksa: ~/gl-q01/m03-l02
learner@ksa:~/gl-q01/m03-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m03-l02./verifyEvents blocked=1 audit=3 keys=2 paints=1 drained=2learner@ksa:~/gl-q01/m03-l02
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets234/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Confirming LIFO Interception and Repaint Coalescing

strace — learner@ksa: ~/gl-q01/m03-l02
learner@ksa:~/gl-q01/m03-l02strace -e trace=write,exit_group ./verifywrite(1, "Events blocked=1 audit=3 keys=2 "..., 51) = 51exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets235/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Blank Widgets From Bad Filters & Nested processEvents() Re-Entrancy

  • You now control every stage of QEvent delivery: stack sendEvent versus heap postEvent, `LowEventPrior…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets236/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Blank Widgets From Bad Filters & Nested processEvents() Re-Entrancy

  • Next, Lesson 3.3 completes Module 3 by connecting the event loop to hardware time: CLOCK_MONOTONIC timer…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets237/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: After installing a custom eventFilter on a QLineEdit or QPushButton, the widget turns completely blank and ignores mouse clicks and focus. - Root Cause: Returning true on the default path tells QCoreApplication::notify that EVERY event—including QEvent::Paint, QEvent::Resize, and QEvent::MouseButtonPress—was consumed! - Fix: Return true ONLY inside the narrow if (...) branch that intentionally blocks an event, and always end with return QObject::eventFilter(watched, event); (false).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets238/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: An engineer adds QCoreApplication::processEvents() inside a file-export slot to 'keep the UI responsive', and clicking Close mid-export crashes inside the still-running export loop! - Root Cause: processEvents() spins a nested event loop right inside your active stack frame, allowing user clicks or DeferredDelete events to re-enter slots or destroy this before the outer loop finishes! - Fix: Never patch slow GUI-thread work with processEvents(); move blocking I/O or heavy math onto a worker thread (or chunk small non-blocking steps on a 0 ms / periodic QTimer).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets239/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Guided Practice

  • Modify install_event_filter in verify.cpp to verify what happens when the SAME filter &audit is insta…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets240/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Independent Practice

  • Design an inactivity screen-dimmer IdleTouchFilter installed once on QApplication::instance() (global a…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets241/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Quick check

What happens if an engineer writes QEvent ev(QEvent::User); QCoreApplication::postEvent(panel, &ev);?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets242/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Quick check

Filter Logger is installed first via btn->installEventFilter(logger), followed by btn->installEventFilter(interlock). When interlock->eventFilter returns true, what executes?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets243/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Quick check

Why should a 500 Hz telemetry slot call gauge->update() rather than gauge->repaint()?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets244/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Summary

  • QCoreApplication::sendEvent(dst, &ev) dispatches a stack-allocated QEvent synchronously on the current call stack without deleting ev, whereas postEvent(dst, new Ev) queues a heap event asynchronously and deletes it after delivery.
  • Passing the address of a stack-allocated QEvent into QCoreApplication::postEvent causes fatal heap corruption when the event dispatcher drains the queue and executes delete event.
  • Pre-target watchers installed via target->installEventFilter(filterObj) execute in LIFO order (last installed runs first); returning true consumes the event immediately while returning false forwards it toward target->event().
  • Qt compresses queued QEvent::UpdateRequest events posted by QWidget::update() so bursts of state changes within one event-loop turn coalesce into a single QPaintEvent raster pass.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets245/570

GL-Q01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Key takeaways

  • Passing the address of a stack-allocated QEvent into QCoreApplication::postEvent causes fatal heap corruption when the event dispatcher drains the queue and executes delete event.
  • Pre-target watchers installed via target->installEventFilter(filterObj) execute in LIFO order (last installed runs first); returning true consumes the event immediately while returning false forwards it toward target->event().
  • Qt compresses queued QEvent::UpdateRequest events posted by QWidget::update() so bursts of state changes within one event-loop turn coalesce into a single QPaintEvent raster pass.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets246/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Monotonic QTimer, Precise vs Coarse Coalescing & GUI Frame Stalls

free preview30 minlab lab_m03_event_loop_timers

What you'll learn

  • Prove why CLOCK_MONOTONIC phase-locked advancement (deadline += period) eliminates cumulative drift and survives NTP wall-clock jumps.
  • Select Qt::PreciseTimer versus Qt::CoarseTimer (5% coalescing window) and bind QTimer::singleShot safely to receiver lifetimes.
  • Instrument GUI slot execution budgets with QElapsedTimer to catch main-thread stalls that starve QPaintEvent / WM_PAINT delivery.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets247/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Wall-Clock Jumps, 5% Timer Jitter & Cooperative Frame Starvation

  • Embedded Linux panels frequently boot with 1970-01-01 RTC time before chronyd steps CLOCK_REALTIME fo…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets248/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Wall-Clock Jumps, 5% Timer Jitter & Cooperative Frame Starvation

  • Even on CLOCK_MONOTONIC, three behaviors catch engineers off guard.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets249/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Wall-Clock Jumps, 5% Timer Jitter & Cooperative Frame Starvation

fig_m03_l03_a.svg

Figure 3.3a: GUI-thread QTimers and QPaintEvents share one cooperative thread: blocking any slot freezes both timers and screen repaints.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets250/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Mental model

note: Phase-locked CLOCK_MONOTONIC scheduling (next += 20 ms) is like a metro line dispatching trains at :00, :20, and :40 off an atomic station clock rather than starting a 20-minute kitchen timer after each train finishes boarding—and if a blocked track holds the platform until :52, the dispatcher skips missed :20/:40 slots and schedules :60 cleanly instead of launching three trains bumper-to-bumper.

Where it stops working: Even Qt::PreciseTimer in standard user space is bounded by Linux kernel scheduler wakeup jitter (typically 50-500 us on normal kernels); sub-50 us deterministic control loops belong on a PREEMPT_RT SCHED_FIFO worker thread or dedicated microcontroller, never on the GUI rendering thread.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets251/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

QTimerInfoList, Qt::TimerType, and QElapsedTimer

definition: QTimerInfoList is Qt's per-thread monotonic deadline queue feeding the timeout parameter of ppoll() / epoll_wait(). Qt::TimerType selects wakeup rounding: Qt::PreciseTimer preserves exact millisecond/nanosecond deadlines, Qt::CoarseTimer (default) adjusts intervals by up to 5% to align neighboring timers, and Qt::VeryCoarseTimer snaps to whole seconds. QElapsedTimer is an allocation-free 8-byte wrapper over clock_gettime(CLOCK_MONOTONIC).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets252/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Wall-Clock Jumps, 5% Timer Jitter & Cooperative Frame Starvation

Call setTimerType(Qt::PreciseTimer) before start() whenever +/-5% coarse jitter is unacceptable.

Use CLOCK_MONOTONIC phase grids, PreciseTimer for cadence, and <8 ms GUI slots so Paint runs.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets253/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

How Blocking Slots Starve Both QTimerInfoList and QPaintEvent

  • Trace one turn of QApplication::exec() on a 60 Hz (16.67 ms period) industrial touchscreen: (1) `epoll_…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets254/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

How Blocking Slots Starve Both QTimerInfoList and QPaintEvent

  • If step (2) performs a synchronous 90 ms serial retry or unindexed SQLite scan, step (4) cannot execute f…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets255/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

How Blocking Slots Starve Both QTimerInfoList and QPaintEvent

fig_m03_l03_b.svg

Figure 3.3b: Keeping GUI-thread slots under 4-8 ms leaves ample headroom inside each 16.67 ms VSync interval for layout and QPainter rasterization.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets256/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

monotonic_frame_watchdog.cpp

learner@ksa: ~/gl-q01/m03-l03
learner@ksa:~/gl-q01/m03-l03$ bat monotonic_frame_watchdog.cpp File: monotonic_frame_watchdog.cpp    #include <QElapsedTimer>    #include <QObject>    #include <QTimer>    #include <cstdint>        namespace hmi {        class FrameWatchdog final : public QObject {        Q_OBJECT    public:        static constexpr int kPeriodMs = 20;        static constexpr std::int64_t kSlotBudgetUs = 8000; // 8 ms (< 16.67 ms 60 Hz)            explicit FrameWatchdog(QObject *parent = nullptr)
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets257/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

QTimer-QElapsedTimer

QTimer-QElapsedTimer(3qt) at a glance — GL-Q01
QTimer-QElapsedTimer(3qt)   GL-Q01 Quick Reference   QTimer-QElapsedTimer(3qt) NAME       QTimer, QElapsedTimer, Qt::TimerType - monotonic scheduling & stall       measurement SYNOPSIS       void QTimer::setTimerType(Qt::TimerType atype); // PreciseTimer | CoarseTimer       static void QTimer::singleShot(int msec, const QObject *context, Functor slot);       qint64 QElapsedTimer::nsecsElapsed() const noexcept;        MONOTONICITY & COOPERATIVE LOOP RULES 1. Both QTimer and QElapsedTimer       use CLOCK_MONOTONIC (immune to NTP jumps). 2. Default Qt::CoarseTimer       coalesces deadlines within a 5% interval window. 3. A GUI-thread QTimer       cannot preempt a busy slot; blocking the main thread starves both       QTimer callbacks and QPaintEvent (WM_PAINT) frame rendering. Kernel Systems Academy            m03-l03            QTimer-QElapsedTimer(3qt) GL-Q01 quick reference · full manual page: man 3qt QTimer-QElapsedTimer 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets258/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Proving Monotonic Phase-Lock, 5% Coarse Window & Paint Starvation in C++20

  • In verify.cpp, we invoke the Linux kernel SYS_clock_gettime syscall with CLOCK_MONOTONIC directly s…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets259/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m03-l03
learner@ksa:~/gl-q01/m03-l03$ bat verify.cpp File: verify.cpp    #include <cassert>    #include <cstdint>    #include <cstdio>    #include <ctime>    #include <functional>    #include <memory>    #include <sys/syscall.h>    #include <unistd.h>    #include <vector>        namespace hmi {        enum class TimerMode { Precise, Coarse };
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets260/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Inspecting CLOCK_MONOTONIC Syscalls and Post-Stall Phase Alignment

  • Inspect both ./verify stdout and the strace capture!
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets261/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Inspecting CLOCK_MONOTONIC Syscalls and Post-Stall Phase Alignment

  • In strace, confirm the two real clock_gettime(CLOCK_MONOTONIC, ...) kernel calls preceding `write(1, ..…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets262/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Inspecting CLOCK_MONOTONIC Syscalls and Post-Stall Phase Alignment

learner@ksa: ~/gl-q01/m03-l03
learner@ksa:~/gl-q01/m03-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m03-l03./verifyTimer mono_dt=579ns coarse50=2500us grid=4 oneshot_cancelled=1 next=140mslearner@ksa:~/gl-q01/m03-l03
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets263/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Inspecting CLOCK_MONOTONIC Syscalls and Post-Stall Phase Alignment

strace — learner@ksa: ~/gl-q01/m03-l03
learner@ksa:~/gl-q01/m03-l03strace -e trace=clock_gettime,write,exit_group \./verifyclock_gettime(CLOCK_MONOTONIC, {tv_sec=1136271, tv_nsec=834146}) = 0clock_gettime(CLOCK_MONOTONIC, {tv_sec=1136271, tv_nsec=893476}) = 0write(1, "Timer mono_dt=59330ns coarse50=2"..., 76) = 76exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets264/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

0-ms Busy Spin Timers, Contextless singleShot & Wall-Clock Timeouts

  • You have now mastered Qt 6's entire core runtime triad across Modules 1–3: C++20 RAII + QObject ownership…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets265/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

0-ms Busy Spin Timers, Contextless singleShot & Wall-Clock Timeouts

  • Complete the lab_m03_event_loop_timers studio below to integrate priority posted events, LIFO filters, an…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets266/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: top shows the HMI binary pegged at 100% CPU usage on one Cortex-A7 core even when nothing on screen is changing, overheating the enclosure. - Root Cause: A 0 ms periodic QTimer fires every single time the event queue finishes draining normal events, preventing ppoll() / epoll_wait() from ever sleeping in the kernel! - Fix: Use QTimer::singleShot(0, this, slot) ONLY for one-time deferred post-construction work; drive recurring polls with explicit frame/sensor periods (20-100 ms) or QSocketNotifier fd readiness.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets267/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Closing a transient notification toast within 500 ms of opening it causes a segmentation fault half a second later inside the fade-out lambda. - Root Cause: Just like 3-argument QObject::connect, 2-argument QTimer::singleShot(msec, functor) has NO context QObject * and fires unconditionally after msec even if this was deleted! - Fix: Always call the 3-argument overload QTimer::singleShot(500, this, [this] { ... }) (or &Toast::fadeOut) so ~Toast() cancels the timer automatically.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets268/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Guided Practice

  • Add a simulated NTP backward wall-clock jump (realtime_offset_ns -= 30 * 1000000000ULL) to verify.cpp a…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets269/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Independent Practice

  • Open labs/lab_m03_event_loop_timers/ and repair all three defects in starter/core.cpp—inverted FIFO fil…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets270/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Quick check

A GUI-thread QTimer runs with Qt::PreciseTimer at 10 ms, and a button slot on the GUI thread executes a synchronous 120 ms CRC scan over a firmware file. How many times do QTimer::timeout and QWidget::paintEvent run during those 120 ms?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets271/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Quick check

What is the default Qt::TimerType of a newly constructed QTimer, and how does it schedule intervals?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets272/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Quick check

Why is QTimer::singleShot(300, this, &Dialog::autoClose) safer than QTimer::singleShot(300, [this] { autoClose(); })?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets273/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Lab: lab_m03_event_loop_timers

  • Industrial HMIs fail intermittent soak tests when a safety eventFilter runs in the wrong order, periodic…

Verify: ./check.sh exits 0.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets274/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Summary

  • QTimer and QElapsedTimer schedule deadlines on CLOCK_MONOTONIC, advancing periodic targets phase-locked (next_ns += period_ns) so NTP or operator wall-clock jumps never freeze or burst HMI timers.
  • QTimer defaults to Qt::CoarseTimer, which rounds wakeups within a 5% interval window to batch OS wakeups; deterministic control/telemetry cadences require setTimerType(Qt::PreciseTimer).
  • Context-bound QTimer::singleShot(ms, receiver, slot) cancels pending one-shot callbacks automatically if receiver is destroyed before the deadline expires.
  • Because QTimer and QPaintEvent (WM_PAINT / UpdateRequest) share the cooperative GUI event loop, blocking a GUI-thread slot for 90 ms delays every GUI QTimer and freezes frame rendering for 90 ms.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets275/570

GL-Q01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Key takeaways

  • QTimer defaults to Qt::CoarseTimer, which rounds wakeups within a 5% interval window to batch OS wakeups; deterministic control/telemetry cadences require setTimerType(Qt::PreciseTimer).
  • Context-bound QTimer::singleShot(ms, receiver, slot) cancels pending one-shot callbacks automatically if receiver is destroyed before the deadline expires.
  • Because QTimer and QPaintEvent (WM_PAINT / UpdateRequest) share the cooperative GUI event loop, blocking a GUI-thread slot for 90 ms delays every GUI QTimer and freezes frame rendering for 90 ms.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets276/570

m04/

>_ Kernel Systems Academy

Button Interlocks, Input Validators & Geometry Layout Solvers

Engineer interlock-safe Qt 6 button groups and touch targets, feedback-free QValidator and QSignalBlocker editors, and drift-free integer box/grid/form layout geometry solvers.

  1. 4.1 Buttons, Checkable Groups & Safety Interlocks
  2. 4.2 Numeric/Text Editors, QValidator States & QSignalBlocker Anti-Echo
  3. 4.3 QBoxLayout, QGridLayout, QFormLayout, QSpacerItem & Stretch Solvers

lab → Lab 4: 1D/2D Box & Grid Layout Geometry Solver with Max-Cap Redistribution

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets277/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Buttons, Checkable Groups & Safety Interlocks

free preview35 min

What you'll learn

  • Enforce two-step Disarmed -> Armed -> Actuated -> Tripped safety interlocks across QPushButton, QToolButton, and QAction with setAutoRepeat(false).
  • Coordinate layout-independent QRadioButton mutual exclusion via QButtonGroup, hierarchical QCheckBox tristate rollups, and QDialogButtonBox role ordering.
  • Distinguish interactive clicked(bool) from programmatic toggled(bool) while sizing 44x44 px minimum touch targets for gloved operators.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets278/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Multi-Surface Command Drift, Auto-Repeat Bounce, and Touch Ergonomics

  • Industrial control panels routinely expose the same actuator command through three entry points: a header `…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets279/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Multi-Surface Command Drift, Auto-Repeat Bounce, and Touch Ergonomics

  • QAction eliminates command drift by owning the authoritative enabled, checked, text, icon, and `QKe…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets280/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Multi-Surface Command Drift, Auto-Repeat Bounce, and Touch Ergonomics

  • Physical panels add two tactile hazards that desktop apps ignore.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets281/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Multi-Surface Command Drift, Auto-Repeat Bounce, and Touch Ergonomics

fig_m04_l01_a.svg

Figure 4.1a: Actuator command path from touch target geometry through QButtonGroup and QAction interlocks.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets282/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Mental model

note: A guarded aircraft cockpit switch places a spring-loaded red cover over the starter toggle: an operator must deliberately flip the cover open (Armed) before actuating the starter (Actuated), and slamming the fire-handle emergency stop snaps every cover shut (Tripped) in a single motion regardless of mode.

Where it stops working: Physical cockpit toggles offer mechanical spring detents, whereas capacitive touchscreens synthesize rapid autoRepeat pulses under a resting gloved thumb unless setAutoRepeat(false) is explicitly set.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets283/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

QButtonGroup & Two-Step Actuator Interlock

definition: In QtWidgets, QButtonGroup inherits directly from QObject (not QWidget) to decouple logical mutual exclusion and integer button IDs from visual QLayout hierarchy. Paired with a QAction-backed two-step interlock (Arm checkable latch gating Start, setAutoRepeat(false), and >= 44x44 px minimum hit boxes), it prevents single-tap actuation, multi-entry shortcut drift, and programmatic toggled loops.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets284/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Multi-Surface Command Drift, Auto-Repeat Bounce, and Touch Ergonomics

Attach mode QRadioButton controls to a QObject-based QButtonGroup so layout placement never breaks mutual exclusion.

Gate hazardous actions via Arm + QAction, disable autoRepeat, and size 44x44 px targets.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets285/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

QButtonGroup Exclusivity, Tristate QCheckBox, and QDialogButtonBox Roles

  • Beginners often assume QRadioButton mutual exclusion requires wrapping buttons inside one QGroupBox.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets286/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

QButtonGroup Exclusivity, Tristate QCheckBox, and QDialogButtonBox Roles

  • When a parent control summarizes multiple child subsystems (such as four cooling-zone valves), a binary che…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets287/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

QButtonGroup Exclusivity, Tristate QCheckBox, and QDialogButtonBox Roles

  • Finally, distinguish clicked(bool) from toggled(bool) on checkable buttons, and use QDialogButtonBox…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets288/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

QButtonGroup Exclusivity, Tristate QCheckBox, and QDialogButtonBox Roles

fig_m04_l01_b.svg

Figure 4.1b: Qt 6 button widget contracts, tristate rollup encodings, and semantic dialog roles.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets289/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

interlock_button_panel.cpp

learner@ksa: ~/gl-q01/m04-l01
learner@ksa:~/gl-q01/m04-l01$ bat interlock_button_panel.cpp File: interlock_button_panel.cpp    #include <QAction>    #include <QButtonGroup>    #include <QCheckBox>    #include <QDialogButtonBox>    #include <QHBoxLayout>    #include <QKeySequence>    #include <QPushButton>    #include <QRadioButton>    #include <QToolButton>    #include <QVBoxLayout>    #include <QWidget>    #include <array>        class SpindleSafetyBar final : public QWidget {
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets290/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

QAbstractButton-QButtonGroup

QAbstractButton-QButtonGroup(3qt) at a glance — GL-Q01
QAbstractButton-QButtonGroup(3qt) GL-Q01 Quick Reference QAbstractButton-QButtonGroup(3qt) NAME       QAbstractButton, QButtonGroup, QCheckBox, QDialogButtonBox - Qt 6       button & interlock contracts SYNOPSIS       btn->setAutoRepeat(false);              // mandatory on safety-relevant actuators       btn->setMinimumSize(44, 44);            // minimum gloved capacitive touch target       grp->addButton(radioBtn, ModeManual);   // explicit ID independent of QLayout parent       chk->setCheckState(Qt::PartiallyChecked);       toolBtn->setDefaultAction(startAction); // unifies shortcut, menu, and button enablement SIGNAL INVARIANTS       clicked(bool) Interactive user press/release or Space key only       toggled(bool) Fires on BOTH user click AND programmatic setChecked()       checkStateChanged(state) Qt 6.8 typed replacement for legacy       stateChanged(int) Kernel Systems Academy        m04-l01        QAbstractButton-QButtonGroup(3qt) GL-Q01 quick reference · full manual page: man 3qt QAbstractButton-QButtonGroup 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets291/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Host C++20 Verifier for Two-Step Interlocks, Button Groups, and Tristate Rollups

  • Before deploying operator controls onto a touchscreen panel, every state transition—mode exclusivity, subsy…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets292/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Host C++20 Verifier for Two-Step Interlocks, Button Groups, and Tristate Rollups

  • Inspect verify.cpp below.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets293/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m04-l01
learner@ksa:~/gl-q01/m04-l01$ bat verify.cpp File: verify.cpp    #include <array>    #include <cassert>    #include <cstdio>        enum class CheckState : int { Unchecked = 0, PartiallyChecked = 1, Checked = 2 };    enum class Interlock : int { Disarmed = 0, Armed = 1, Tripped = 2 };        struct TouchBox {        int width_px;        int height_px;        constexpr bool meets_hmi_minimum() const noexcept {            return width_px >= 44 && height_px >= 44;        }    };
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets294/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Verifying Interlock Transitions, Auto-Repeat Rejection, and Tristate Output

  • Compile and execute verify.cpp under strict -std=c++20 -Wall -Wextra -Werror -pedantic.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets295/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Verifying Interlock Transitions, Auto-Repeat Rejection, and Tristate Output

  • Notice the safety invariant verified at the end of main(): tripping E-Stop while Armed and then acknowl…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets296/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Verifying Interlock Transitions, Auto-Repeat Rejection, and Tristate Output

learner@ksa: ~/gl-q01/m04-l01
learner@ksa:~/gl-q01/m04-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m04-l01./verifybuttons_audit: mode_id=2 tristate_part=1 actuations=1 repeats_blocked=1 reset_disarmed=1learner@ksa:~/gl-q01/m04-l01
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets297/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Verifying Interlock Transitions, Auto-Repeat Rejection, and Tristate Output

strace — learner@ksa: ~/gl-q01/m04-l01
learner@ksa:~/gl-q01/m04-l01strace -e trace=write,exit_group ./verifywrite(1, "buttons_audit: mode_id=2 tristat"..., 89) = 89exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets298/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Common HMI Defects in Button Signals, Radio Grouping, and Touch Sizing

  • Hardening button and action topologies removes whole classes of field operator incidents before layout or s…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets299/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Common HMI Defects in Button Signals, Radio Grouping, and Touch Sizing

  • Remember the host-versus-target boundary: host C++20 verification proves state-machine transitions and `>=…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets300/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Calling armBtn->setChecked(false) during an E-Stop or fault reset unexpectedly transmits a CAN bus arm/disarm command frame or re-triggers confirmation dialogs. - Root Cause: QAbstractButton::toggled(bool) emits on every state change including programmatic setChecked(), whereas clicked(bool) emits exclusively on user interaction. - Fix: Bind interactive operator commands to clicked(bool) (or wrap programmatic state synchronization in QSignalBlocker).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets301/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Placing two independent pairs of QRadioButton controls inside one QFrame causes clicking a button in pair B to uncheck the active selection in pair A. - Root Cause: With autoExclusive enabled and no QButtonGroup assigned, QRadioButton treats all autoExclusive siblings sharing the same parent QWidget as one single group. - Fix: Create one explicit QButtonGroup(this) per logical radio set and register members via group->addButton(radio, enumId).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets302/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Guided Practice

  • Extend InterlockHarness in verify.cpp so trigger_start_action also requires `ExclusiveButtonGroup::ch…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets303/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Independent Practice

  • Design a C++20 bidirectional tristate controller for an 8-channel alarm mask where clicking the parent `Che…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets304/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Quick check

An engineer connects connect(armBtn, &QPushButton::toggled, this, &Panel::sendArmFrame) and calls armBtn->setChecked(false) inside an E-Stop handler. What happens?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets305/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Quick check

Why bind a QToolButton, a QMenu entry, and an F5 shortcut to one shared QAction via setDefaultAction?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets306/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Quick check

How does QButtonGroup allow mutually exclusive QRadioButton controls to sit inside different QHBoxLayout or QFrame containers?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets307/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Summary

  • Disabling autoRepeat on safety-critical QPushButton and QToolButton actuators prevents a held finger or key bounce from synthesizing repeated clicked() pulses while enforcing at least 44x44 px capacitive touch targets.
  • QButtonGroup is a non-visual QObject container that enforces QRadioButton or checkable button mutual exclusion and integer ID dispatch (idClicked) across arbitrary layouts without forcing buttons into one visual QGroupBox.
  • QAbstractButton::toggled(bool) emits on both operator clicks and programmatic setChecked() calls, whereas clicked(bool) emits only on interactive user activation (mouse, touch, Space, or click()).
  • A tristate QCheckBox (Qt::Unchecked, Qt::PartiallyChecked, Qt::Checked) summarizes mixed child enablement states, while QDialogButtonBox orders AcceptRole, RejectRole, and DestructiveRole buttons per platform style.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets308/570

GL-Q01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Key takeaways

  • QButtonGroup is a non-visual QObject container that enforces QRadioButton or checkable button mutual exclusion and integer ID dispatch (idClicked) across arbitrary layouts without forcing buttons into one visual QGroupBox.
  • QAbstractButton::toggled(bool) emits on both operator clicks and programmatic setChecked() calls, whereas clicked(bool) emits only on interactive user activation (mouse, touch, Space, or click()).
  • A tristate QCheckBox (Qt::Unchecked, Qt::PartiallyChecked, Qt::Checked) summarizes mixed child enablement states, while QDialogButtonBox orders AcceptRole, RejectRole, and DestructiveRole buttons per platform style.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets309/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Numeric/Text Editors, QValidator States & QSignalBlocker Anti-Echo

free preview35 min

What you'll learn

  • Classify live keystrokes into QValidator::Invalid, Intermediate, and Acceptable states so multi-digit numeric edits progress without premature commits.
  • Eliminate recursive valueChanged ping-pong across coupled QSpinBox, QDoubleSpinBox, QSlider, QDial, QComboBox, and QLineEdit controls using RAII QSignalBlocker.
  • Select QPlainTextEdit (maximumBlockCount) versus QTextEdit/QTextBrowser and fixed-point integer backing to bound RAM and avoid IEEE-754 drift.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets310/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Prefix Validation Automata and Coupled-Control Signal Ping-Pong

  • Consider a manifold pressure QLineEdit constrained to [100, 500] kPa.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets311/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Prefix Validation Automata and Coupled-Control Signal Ping-Pong

  • A companion hazard lurks inside QSpinBox and QDoubleSpinBox: by default, keyboardTracking() is true…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets312/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Prefix Validation Automata and Coupled-Control Signal Ping-Pong

  • Once committed, dashboards often mirror one setpoint across a QSpinBox, a coarse QSlider or QDial, an…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets313/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Prefix Validation Automata and Coupled-Control Signal Ping-Pong

fig_m04_l02_a.svg

Figure 4.2a: Keystroke validation and multi-widget setpoint synchronization without recursive signal echo.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets314/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Mental model

note: QValidator::Intermediate works like an airlock keypad expecting a three-digit pressure code between 100 and 500: pressing '2' neither buzzes an error nor opens the inner hatch—it holds the latch in an in-progress state until '5' and '0' complete '250' (Acceptable), while rejecting 'x' (Invalid) on sight.

Where it stops working: An airlock keypad is a single input terminal, whereas coupling a QLineEdit, QSpinBox, and quantized QSlider on one screen creates an active feedback loop where one programmatic setValue() echoes back into its sender unless silenced by QSignalBlocker.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets315/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

QSignalBlocker & QValidator::State

definition: QValidator::State (Invalid = 0, Intermediate = 1, Acceptable = 2) models formal prefix-language acceptance so QLineEdit permits valid prefixes ("", "-", "25" on [100, 500]) while gating editingFinished() on Acceptable. QSignalBlocker is a non-copyable C++ RAII guard calling m_wasBlocked = obj->blockSignals(true) in its constructor and obj->blockSignals(m_wasBlocked) in its destructor.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets316/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Prefix Validation Automata and Coupled-Control Signal Ping-Pong

Let QValidator::Intermediate pass valid numeric prefixes without firing editingFinished prematurely.

Gate commits on QValidator::Acceptable, sync peers with QSignalBlocker, and cap logs.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets317/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

QSignalBlocker RAII, QPlainTextEdit vs QTextBrowser, and Typed Selectors

  • Legacy code often wraps programmatic updates in `slider->blockSignals(true); slider->setValue(v); slider->b…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets318/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

QSignalBlocker RAII, QPlainTextEdit vs QTextBrowser, and Typed Selectors

  • For multi-line text, pick the engine that matches the workload.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets319/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

QSignalBlocker RAII, QPlainTextEdit vs QTextBrowser, and Typed Selectors

  • Round out forms with typed selectors: pass QVariant integer IDs to `QComboBox::addItem(tr("psi"), UnitPsi…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets320/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

QSignalBlocker RAII, QPlainTextEdit vs QTextBrowser, and Typed Selectors

fig_m04_l02_b.svg

Figure 4.2b: Memory and precision contracts across Qt 6 text, numeric, selector, and log widgets.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets321/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

coupled_setpoint_console.cpp

learner@ksa: ~/gl-q01/m04-l02
learner@ksa:~/gl-q01/m04-l02$ bat coupled_setpoint_console.cpp File: coupled_setpoint_console.cpp    #include <QComboBox>    #include <QDateTime>    #include <QDateTimeEdit>    #include <QDial>    #include <QHBoxLayout>    #include <QIntValidator>    #include <QLineEdit>    #include <QPlainTextEdit>    #include <QSignalBlocker>    #include <QSlider>    #include <QSpinBox>    #include <QTimeZone>    #include <QVBoxLayout>    #include <QWidget>
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets322/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

QValidator-QSignalBlocker

QValidator-QSignalBlocker(3qt) at a glance — GL-Q01
QValidator-QSignalBlocker(3qt) GL-Q01 Quick Reference QValidator-QSignalBlocker(3qt) NAME       QValidator, QSignalBlocker, QPlainTextEdit - input validation,       anti-echo sync, and bounded logs SYNOPSIS       const QSignalBlocker blocker(peerWidget); // RAII: saves & restores       prior signalsBlocked() spin->setKeyboardTracking(false); // emit       valueChanged only on commit or step combo->addItem(tr("kPa"), UnitKpa);       // read via combo->currentData().toInt()       log->setMaximumBlockCount(500); // evicts oldest paragraph block       automatically QVALIDATOR STATES       QValidator::Invalid Reject keystroke immediately; buffer unchanged       QValidator::Intermediate Permit prefix edit in buffer; suppress       editingFinished() QValidator::Acceptable In-range token; enables       editingFinished() / returnPressed() Kernel Systems Academy         m04-l02          QValidator-QSignalBlocker(3qt) GL-Q01 quick reference · full manual page: man 3qt QValidator-QSignalBlocker 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets323/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Host C++20 Verifier for Range Validators, SignalBlocker Nesting, and Bounded Logs

  • Let us verify all three editor invariants in a self-contained ISO C++20 harness: prefix classification on `…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets324/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Host C++20 Verifier for Range Validators, SignalBlocker Nesting, and Bounded Logs

  • Examine RangeValidator::validate in verify.cpp: '2' and '25' have fewer digits than 500 (3 digi…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets325/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m04-l02
learner@ksa:~/gl-q01/m04-l02$ bat verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cctype>    #include <cstdio>    #include <deque>    #include <functional>    #include <string>    #include <string_view>        enum class ValState { Invalid, Intermediate, Acceptable };        class RangeValidator {    public:        constexpr RangeValidator(int lo, int hi) noexcept : m_lo(lo), m_hi(hi) {}
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets326/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Inspecting Anti-Echo Counts, Validator Transitions, and Log Eviction

  • Run ./verify and confirm spin=243 slider=240 commits=1 nested_kept=1 log_blocks=4 oldest=seq_4.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets327/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Inspecting Anti-Echo Counts, Validator Transitions, and Log Eviction

  • Meanwhile, appending 7 lines into PlainLogRing(4) capped memory at 4 blocks with seq_4 at the head—…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets328/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Inspecting Anti-Echo Counts, Validator Transitions, and Log Eviction

learner@ksa: ~/gl-q01/m04-l02
learner@ksa:~/gl-q01/m04-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m04-l02./verifyeditors_audit: spin=243 slider=310 commits=1 nested_kept=1 log_blocks=4 oldest=seq_4learner@ksa:~/gl-q01/m04-l02
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets329/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Inspecting Anti-Echo Counts, Validator Transitions, and Log Eviction

strace — learner@ksa: ~/gl-q01/m04-l02
learner@ksa:~/gl-q01/m04-l02strace -e trace=write,exit_group ./verifywrite(1, "editors_audit: spin=243 slider=3"..., 85) = 85exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets330/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Field Pitfalls in Coupled Editors, Rich-Text Logs, and Locale Strings

  • Validating prefixes cleanly, blocking programmatic echo via RAII, and bounding log document growth keep dat…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets331/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Field Pitfalls in Coupled Editors, Rich-Text Logs, and Locale Strings

  • Keep host-versus-target scope explicit: host C++20 tests verify validator automata and signal-graph invaria…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets332/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: After 6 hours of 100 Hz CAN traffic, HMI resident memory climbs past 300 MiB and every append freezes the GUI thread for 40 ms. - Root Cause: QTextEdit builds an unbounded rich-text HTML/CSS QTextDocument layout tree and re-paginates paragraphs on append. - Fix: Replace QTextEdit with read-only QPlainTextEdit and call setMaximumBlockCount(500) to bound RAM in O(1) time.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets333/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Switching the HMI locale to German ('Kilopascal' or 'Aus') silently falls through unit-conversion branches and sends zeroed setpoints. - Root Cause: currentText() returns the user-visible tr() translated string rather than a language-invariant identifier. - Fix: Store enum constants via combo->addItem(tr("..."), UnitKpa) and branch exclusively on combo->currentData().toInt().

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets334/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Guided Practice

  • Extend RangeValidator in verify.cpp to support signed negative temperature ranges [-40, -10] degrees…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets335/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Independent Practice

  • Build a fixed-point CentibarSpinModel storing pressure in int32_t hundredths of a bar ([100, 500] ->…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets336/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Quick check

With QIntValidator(100, 500) attached to a QLineEdit, what does validate("25", pos) return while the operator types '2', '5', '0'?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets337/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Quick check

Why is const QSignalBlocker b(widget); strictly safer than widget->blockSignals(true); ... widget->blockSignals(false);?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets338/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Quick check

Which widget and configuration should display a continuous 200 lines/sec diagnostic UART trace on a 512 MiB embedded Linux panel?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets339/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Summary

  • QValidator classifies input strings into Invalid (rejected immediately), Intermediate (permitted while typing toward a valid value while suppressing editingFinished()), and Acceptable (eligible to commit).
  • Stack-scoped QSignalBlocker suppresses intermediate signal emissions during programmatic peer-widget updates and restores the widget's prior signalsBlocked() boolean on scope exit.
  • QPlainTextEdit with setMaximumBlockCount() stores line-oriented logs in bounded plain-text blocks (O(1) eviction), whereas QTextEdit and QTextBrowser maintain a full rich-text QTextDocument layout tree.
  • Attaching typed QVariant user data to QComboBox::addItem(), setting QSpinBox::setKeyboardTracking(false), and pinning QDateTimeEdit to QTimeZone::UTC prevent locale drift and half-typed setpoint spikes.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets340/570

GL-Q01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Key takeaways

  • Stack-scoped QSignalBlocker suppresses intermediate signal emissions during programmatic peer-widget updates and restores the widget's prior signalsBlocked() boolean on scope exit.
  • QPlainTextEdit with setMaximumBlockCount() stores line-oriented logs in bounded plain-text blocks (O(1) eviction), whereas QTextEdit and QTextBrowser maintain a full rich-text QTextDocument layout tree.
  • Attaching typed QVariant user data to QComboBox::addItem(), setting QSpinBox::setKeyboardTracking(false), and pinning QDateTimeEdit to QTimeZone::UTC prevent locale drift and half-typed setpoint spikes.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets341/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

QBoxLayout, QGridLayout, QFormLayout, QSpacerItem & Stretch Solvers

free preview30 minlab lab_m04_box_grid_layout_solver

What you'll learn

  • Derive exact 1D/2D widget positions and sizes from margins, visible-only spacing gaps, sizeHint(), minimumSizeHint(), and QSizePolicy.
  • Distribute surplus pixels across integer stretch weights with maxSize cap redistribution and remainder rounding so zero cumulative drift occurs.
  • Structure aligned multi-channel readouts and calibration dialogs using QGridLayout, QFormLayout, and QSpacerItem without nested parent collisions.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets342/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Why Magic Pixel Coordinates Break and How QLayoutEngine Solves Constraints

  • Hardcoding btn->setGeometry(16, 420, 110, 36) looks fine on one workstation monitor at 96 DPI and break…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets343/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Why Magic Pixel Coordinates Break and How QLayoutEngine Solves Constraints

  • Qt's layout engine (qGeomCalc) replaces fixed coordinates with a deterministic 1D/2D constraint solver.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets344/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Why Magic Pixel Coordinates Break and How QLayoutEngine Solves Constraints

  • Walk the exact 1D equation for N_vis visible items inside width W with margins m_L, m_R and spacing `…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets345/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Why Magic Pixel Coordinates Break and How QLayoutEngine Solves Constraints

fig_m04_l03_a.svg

Figure 4.3a: Constraint-based geometry calculation across visible items, size policies, and stretch remainders.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets346/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Mental model

note: A QBoxLayout works like snapping components onto a steel DIN rail inside an electrical cabinet: fixed-width circuit breakers claim their exact millimeter footprint first, maximum-capped terminal blocks stop growing at their housing limit, and expandable wire ducts split every remaining millimeter flush to the end stop.

Where it stops working: Steel DIN rails tolerate fractional millimeter tolerances, whereas LCD panels address discrete integer pixels—splitting 100 surplus pixels across three equal stretch = 1 columns (34 + 33 + 33 = 100) requires explicit remainder distribution so a 2-pixel dead gap never opens on the right margin.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets347/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

QSizePolicy & Integer Stretch Solver

definition: QSizePolicy pairs per-axis bitflags (GrowFlag = 1, ExpandFlag = 2, ShrinkFlag = 4, IgnoreFlag = 8) into standard modes (Fixed = 0, Minimum = Grow, Preferred = Grow|Shrink, Expanding = Grow|Shrink|Expand). Inside qGeomCalc, positive integer stretch factors override ExpandFlag priority, iterative capping redistributes overflow when an item hits maximumSize(), and integer remainder distribution prevents cumulative drift.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets348/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Why Magic Pixel Coordinates Break and How QLayoutEngine Solves Constraints

Compute usable span U from visible items only: hidden widgets contribute 0 px size and 0 spacing gaps.

Ban magic setGeometry(); use QGridLayout/QFormLayout, QSizePolicy, and stretch weights.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets349/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Stretch Remainder Math, QGridLayout vs QFormLayout, and QSpacerItem

  • When usable width U exceeds the sum of clamped sizeHint() widths, QLayoutEngine allocates surplus S…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets350/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Stretch Remainder Math, QGridLayout vs QFormLayout, and QSpacerItem

  • Select the right container for 2D alignment.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets351/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Stretch Remainder Math, QGridLayout vs QFormLayout, and QSpacerItem

  • To push buttons to the right or bottom edge without allocating an empty QWidget, insert a QSpacerItem (…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets352/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Stretch Remainder Math, QGridLayout vs QFormLayout, and QSpacerItem

fig_m04_l03_b.svg

Figure 4.3b: Choosing between QBoxLayout, QGridLayout, QFormLayout, and QSpacerItem with QSizePolicy flags.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets353/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

calibration_layout_grid.cpp

learner@ksa: ~/gl-q01/m04-l03
learner@ksa:~/gl-q01/m04-l03$ bat calibration_layout_grid.cpp File: calibration_layout_grid.cpp    #include <QFormLayout>    #include <QGridLayout>    #include <QHBoxLayout>    #include <QLabel>    #include <QPushButton>    #include <QSizePolicy>    #include <QSpacerItem>    #include <QSpinBox>    #include <QVBoxLayout>    #include <QWidget>    #include <array>        class CalibrationTelemetryPanel final : public QWidget {        Q_OBJECT
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets354/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

QLayout-QSizePolicy

QLayout-QSizePolicy(3qt) at a glance — GL-Q01
QLayout-QSizePolicy(3qt)    GL-Q01 Quick Reference    QLayout-QSizePolicy(3qt) NAME       QBoxLayout, QGridLayout, QFormLayout, QSpacerItem, QSizePolicy - Qt 6       geometry solvers SYNOPSIS       auto *root = new QVBoxLayout(this); // ONLY the top-level layout takes       'this' auto *grid = new QGridLayout(); // sub-layouts take no parent;       call root->addLayout(grid) grid->setColumnStretch(1, 1); //       proportional track weight box->addStretch(1); // inserts Expanding       QSpacerItem (zero QWidget overhead)        SOLVER EQUATION (1D AXIS) usable = max(0, total - marginStart -       marginEnd - (N_visible - 1) * spacing) Priority: (1) stretch > 0, (2)       QSizePolicy::Expanding, (3) QSizePolicy::Preferred Kernel Systems Academy            m04-l03             QLayout-QSizePolicy(3qt) GL-Q01 quick reference · full manual page: man 3qt QLayout-QSizePolicy 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets355/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Host C++20 Verifier for Stretch Remainders, Max-Cap Redistribution, and Hidden Items

  • Let us verify the exact integer math of qGeomCalc in verify.cpp: visible-only gap counting, iterative `…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets356/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Host C++20 Verifier for Stretch Remainders, Max-Cap Redistribution, and Hidden Items

  • Trace the three assertions before compiling: 322 px with 10 px margins across three stretch = 1 items…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets357/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m04-l03
learner@ksa:~/gl-q01/m04-l03$ bat verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cstdio>    #include <vector>        enum class Mode { Fixed, Preferred, Expanding };        struct Spec {        int min_px;        int hint_px;        int max_px;        int stretch;        Mode mode;        bool visible;
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets358/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Verifying Exact Edge Alignment, Hidden-Item Gaps, and Cap Saturation

  • Confirm ./verify prints layout_audit: rem=[101,101,100] end=312 hidden_pos2=118 capped=[130,270].
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets359/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Verifying Exact Edge Alignment, Hidden-Item Gaps, and Cap Saturation

  • Now proceed to lab_m04_box_grid_layout_solver to implement and benchmark both 1D deficit/surplus solving…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets360/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Verifying Exact Edge Alignment, Hidden-Item Gaps, and Cap Saturation

learner@ksa: ~/gl-q01/m04-l03
learner@ksa:~/gl-q01/m04-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m04-l03./verifylayout_audit: rem=[101,101,100] end=312 hidden_pos2=118 capped=[130,270]learner@ksa:~/gl-q01/m04-l03
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets361/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Verifying Exact Edge Alignment, Hidden-Item Gaps, and Cap Saturation

strace — learner@ksa: ~/gl-q01/m04-l03
learner@ksa:~/gl-q01/m04-l03strace -e trace=write,exit_group ./verifywrite(1, "layout_audit: rem=[101,101,100] "..., 73) = 73exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets362/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Layout Parenting Errors and Minimum-Size Clipping Pitfalls

  • Constraint-driven layouts let a single Qt 6 widget hierarchy adapt cleanly across compact DIN-rail touchscr…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets363/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Layout Parenting Errors and Minimum-Size Clipping Pitfalls

  • Keep the host-versus-target boundary clear: our CLOCK_MONOTONIC solver benchmark measures pure C++20 inte…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets364/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Qt prints 'QLayout: Attempting to add QLayout "" to Panel "", which already has a layout' and child widgets pile up at (0, 0). - Root Cause: Constructing new QHBoxLayout(this) installs that layout as the widget's sole top-level layout, colliding with new QVBoxLayout(this). - Fix: Pass 'this' only to the root layout; construct nested layouts with empty parentheses new QHBoxLayout() and attach via root->addLayout(sub).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets365/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Complex industrial forms construct dozens of blank dummy QWidget objects just to push buttons right or bottom, inflating QObject tree traversal and style polishing. - Root Cause: Using new QWidget(this) with Expanding policy allocates full QWidgetPrivate structures where a pure geometry spring suffices. - Fix: Call boxLayout->addStretch(1) or gridLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum), r, c).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets366/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Guided Practice

  • Extend solve_axis in verify.cpp to handle container shrinkage (surplus < 0, i.e., avail < sum) by s…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets367/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Independent Practice

  • Complete lab_m04_box_grid_layout_solver by repairing the three defects in starter/core.cpp: excluding h…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets368/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Quick check

An engineer writes auto *root = new QVBoxLayout(this); auto *row = new QHBoxLayout(this); root->addLayout(row);. Why does Qt emit a runtime layout warning?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets369/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Quick check

In a QHBoxLayout containing 4 widgets with spacing = 10, the user hides widget 2 (w2->hide()). How many spacing gaps remain in the horizontal equation?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets370/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Quick check

Three visible items in a QHBoxLayout all have stretch = 0: two use QSizePolicy::Preferred and one uses QSizePolicy::Expanding. How is surplus width distributed?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets371/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Lab: lab_m04_box_grid_layout_solver

  • Build and benchmark a deterministic ISO C++20 1D/2D box-and-grid layout geometry solver that mirrors `QLayo…

Verify: ./check.sh exits 0.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets372/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Summary

  • QLayoutEngine subtracts margins and (N_visible - 1) * spacing first, locks QSizePolicy::Fixed items to sizeHint(), clamps [minimumSize, maximumSize], and divides surplus across stretch factors without cumulative rounding drift.
  • Hidden widgets (!isVisible()) consume zero pixels and zero inter-item spacing gaps, while QSpacerItem (addStretch) absorbs slack space without allocating a QWidget window backing surface.
  • QGridLayout solves shared column and row tracks (setColumnStretch, setRowStretch) across multi-row telemetry cells, whereas QFormLayout pairs two-column label-and-field calibration rows cleanly.
  • Passing a QWidget * constructor argument to a nested sub-layout (new QHBoxLayout(this)) fails because a QWidget owns only one root layout; nested layouts construct parentless and attach via addLayout().
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets373/570

GL-Q01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Key takeaways

  • Hidden widgets (!isVisible()) consume zero pixels and zero inter-item spacing gaps, while QSpacerItem (addStretch) absorbs slack space without allocating a QWidget window backing surface.
  • QGridLayout solves shared column and row tracks (setColumnStretch, setRowStretch) across multi-row telemetry cells, whereas QFormLayout pairs two-column label-and-field calibration rows cleanly.
  • Passing a QWidget * constructor argument to a nested sub-layout (new QHBoxLayout(this)) fails because a QWidget owns only one root layout; nested layouts construct parentless and attach via addLayout().
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets374/570

m05/

>_ Kernel Systems Academy

Container Widgets, QAbstractItemModel Roles & Proxy Views

Bound multi-screen HMI memory via lazy container factories, replace O(R*C) item-widgets with contiguous QAbstractTableModel role projections, and wire zero-copy proxy views, QUndoStack, and delegates.

  1. 5.1 Containers, Display Widgets & Lazy Page Budgets
  2. 5.2 Model/View vs Item-Widgets: QAbstractTableModel, QListView, QTreeView & Roles
  3. 5.3 beginInsertRows Contracts, QSortFilterProxyModel & Custom StyledItemDelegates

lab → Lab 5: Bounded FaultTableModel, Persistent Selection & Sort/Filter Proxy

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets375/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Containers, Display Widgets & Lazy Page Budgets

free preview30 min

What you'll learn

  • Cut cold-boot latency and resident heap usage on embedded panels by lazy-instantiating QStackedWidget and QTabWidget pages on first navigation.
  • Configure QScrollArea::setWidgetResizable(true), QLabel::setTextFormat(Qt::PlainText), QProgressBar, QLCDNumber, QFrame, and checkable QGroupBox safely.
  • Choose cleanly between layout-driven containers (QToolBox, QDockWidget, QMdiArea) and 2D spatial QGraphicsView/QGraphicsScene canvases.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets376/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Cold-Boot Memory Budgets and Choosing the Right Qt 6 Container

  • Full-screen embedded HMIs typically pair a persistent side navigation rail with a central QStackedWidget…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets377/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Cold-Boot Memory Budgets and Choosing the Right Qt 6 Container

  • Registering lightweight std::function<QWidget *(QWidget *)> factories per slot lets MainWindow build on…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets378/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Cold-Boot Memory Budgets and Choosing the Right Qt 6 Container

  • Inside tall configuration pages, QScrollArea clips a large child widget through a scrollable viewport().
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets379/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Cold-Boot Memory Budgets and Choosing the Right Qt 6 Container

fig_m05_l01_a.svg

Figure 5.1a: Cold-boot memory and startup latency savings from lazy QStackedWidget page materialization.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets380/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Mental model

note: Eagerly constructing sixteen hidden calibration, P&ID schematic, and fault-history tabs inside MainWindow at power-on is like energizing every welding bay in a factory at 6:00 AM just in case maintenance opens bay 14 on Friday—lazy factories power the main run console immediately and energize secondary bays on demand.

Where it stops working: Throwing a bay breaker runs independently of the main line, whereas a lazy QWidget factory still executes synchronously on the single GUI thread during first click—so each page build must stay under 16 ms.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets381/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Lazy QStackedWidget Factory & Viewport Containers

definition: QStackedWidget wraps QStackedLayout to keep exactly one child QWidget visible at a time (QTabWidget and QToolBox layer a tab bar or accordion header over an internal QStackedWidget). Replacing lightweight stub QWidget slots via insertWidget + removeWidget + delete on first activation bounds resident QWidgetPrivate heap memory without changing page indices.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets382/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Cold-Boot Memory Budgets and Choosing the Right Qt 6 Container

Populate off-screen QStackedWidget indices with empty QWidget stubs so cold boot builds only page 0.

Build hidden pages lazily, delete stubs, setWidgetResizable(true), and use PlainText.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets383/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Passive Display Hardening, Checkable QGroupBox, and QGraphicsView Overview

  • Passive display widgets carry subtle defaults worth knowing cold.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets384/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Passive Display Hardening, Checkable QGroupBox, and QGraphicsView Overview

  • For collapsible or optional parameter blocks, QGroupBox::setCheckable(true) automatically enables or disa…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets385/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Passive Display Hardening, Checkable QGroupBox, and QGraphicsView Overview

  • When a screen must pan, zoom, and hit-test thousands of interactive 2D symbols—such as valve P&ID diagrams,…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets386/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Passive Display Hardening, Checkable QGroupBox, and QGraphicsView Overview

fig_m05_l01_b.svg

Figure 5.1b: Architectural boundaries across Qt 6 display widgets, multi-page containers, and 2D graphics views.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets387/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

lazy_workbench_containers.cpp

learner@ksa: ~/gl-q01/m05-l01
learner@ksa:~/gl-q01/m05-l01$ bat lazy_workbench_containers.cpp File: lazy_workbench_containers.cpp    #include <QDockWidget>    #include <QFrame>    #include <QGraphicsRectItem>    #include <QGraphicsScene>    #include <QGraphicsView>    #include <QGroupBox>    #include <QHBoxLayout>    #include <QLabel>    #include <QMainWindow>    #include <QProgressBar>    #include <QScrollArea>    #include <QStackedWidget>    #include <QVBoxLayout>    #include <QWidget>
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets388/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

QStackedWidget-QScrollArea

QStackedWidget-QScrollArea(3qt) at a glance — GL-Q01
QStackedWidget-QScrollArea(3qt) GL-Q01 Quick Reference QStackedWidget-QScrollArea(3qt) NAME       QStackedWidget, QScrollArea, QDockWidget, QGraphicsView - Qt 6       container & viewport rules SYNOPSIS       scroll->setWidget(content);       scroll->setWidgetResizable(true);       // default is false!       lbl->setTextFormat(Qt::PlainText);      // safe raw telemetry rendering       dock->setObjectName("BusDock");         // mandatory for QMainWindow::saveState()       m_stack->removeWidget(stub); delete stub; CONTAINER SELECTION       QStackedWidget / QTabWidget Single active page; lazy-build secondary       screens on visit QScrollArea Viewport clipping over tall QLayout forms       QGraphicsView + Scene 2D world coordinates, pan/zoom transforms, 10k+       BSP items Kernel Systems Academy         m05-l01         QStackedWidget-QScrollArea(3qt) GL-Q01 quick reference · full manual page: man 3qt QStackedWidget-QScrollArea 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets389/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Host C++20 Verifier for Lazy Deck RAM Budgets, Stub Cleanup, and Scroll Viewports

  • In verify.cpp, we model an 8-screen LazyStackDeck tracking both resident page memory and live placehold…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets390/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Host C++20 Verifier for Lazy Deck RAM Budgets, Stub Cleanup, and Scroll Viewports

  • Verify the memory trajectory: registering 8 screens of 256 KiB each with only page 0 eager consumes `…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets391/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m05-l01
learner@ksa:~/gl-q01/m05-l01$ bat verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cstddef>    #include <cstdio>    #include <functional>    #include <memory>    #include <string>    #include <vector>        struct BuiltPage {        std::string name;        std::size_t ram_bytes;    };
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets392/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Verifying Startup Memory Savings, Stub Deletion, and Viewport Expansion

  • Run ./verify and confirm `containers_audit: boot_kib=256 active_kib=512 builds=2 stubs=6 scroll_w=1024 ma…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets393/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Verifying Startup Memory Savings, Stub Deletion, and Viewport Expansion

  • Next, what happens inside an Alarms or Telemetry page when 50,000 records must be displayed?
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets394/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Verifying Startup Memory Savings, Stub Deletion, and Viewport Expansion

learner@ksa: ~/gl-q01/m05-l01
learner@ksa:~/gl-q01/m05-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m05-l01./verifycontainers_audit: boot_kib=256 active_kib=512 builds=2 stubs=6 scroll_w=1024 max_y=920learner@ksa:~/gl-q01/m05-l01
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets395/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Verifying Startup Memory Savings, Stub Deletion, and Viewport Expansion

strace — learner@ksa: ~/gl-q01/m05-l01
learner@ksa:~/gl-q01/m05-l01strace -e trace=write,exit_group ./verifywrite(1, "containers_audit: boot_kib=256 a"..., 87) = 87exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets396/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Production Bugs with QScrollArea, removeWidget, and QMainWindow::saveState

  • Lazy container decks bound page-level memory while QScrollArea, QDockWidget, and QGraphicsView partit…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets397/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Production Bugs with QScrollArea, removeWidget, and QMainWindow::saveState

  • Keep host-versus-target evidence separate: host C++20 accounting proves page-allocation counts and viewport…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets398/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Widening a window or deploying to a 1280x800 display leaves the form inside QScrollArea cramped in a 320 px top-left corner. - Root Cause: QScrollArea defaults to widgetResizable == false, preserving the inner widget's initial size() instead of tracking viewport() width. - Fix: Call scrollArea->setWidgetResizable(true) immediately after scrollArea->setWidget(content).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets399/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: QMainWindow::saveState() logs 'QMainWindow::saveState(): 'objectName' not set for QDockWidget' and fails to restore operator dock layouts across reboots. - Root Cause: Qt identifies dock widgets and toolbars inside the serialized QByteArray state blob by QObject::objectName(), which defaults to empty. - Fix: Assign a stable ASCII identifier via dock->setObjectName(QStringLiteral("TelemetryBusDock")) on every QDockWidget and QToolBar.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets400/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Guided Practice

  • Add an evict_inactive_lru() method to LazyStackDeck in verify.cpp that enforces a strict 768 KiB (`…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets401/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Independent Practice

  • Write a C++20 PlainVsAutoText sanitizer check modeling QLabel default AutoText detection (< followe…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets402/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Quick check

After calling m_stack->insertWidget(idx, realPage) and m_stack->removeWidget(oldStub) on a QStackedWidget, why is delete oldStub; still required?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets403/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Quick check

Why should telemetry QLabel controls displaying live serial or CAN strings call setTextFormat(Qt::PlainText)?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets404/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Quick check

When is QGraphicsView + QGraphicsScene strongly preferred over nested QGridLayout widgets?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets405/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Summary

  • Registering C++20 page factories in QStackedWidget and materializing off-screen diagnostics pages on first visit keeps cold-boot RAM and startup latency within embedded budgets.
  • QScrollArea defaults to widgetResizable() == false (freezing inner layouts at initial size unless set true), and QStackedWidget::removeWidget(stub) requires explicit delete stub to free RAM.
  • Setting QLabel::setTextFormat(Qt::PlainText) on live bus strings prevents Qt::AutoText from misinterpreting < brackets in telemetry payloads as rich-text HTML tags.
  • QDockWidget and QMdiArea organize multi-pane engineering workbenches (saveState/restoreState), whereas QGraphicsView indexes thousands of zoomable 2D QGraphicsItem schematics via BSP trees.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets406/570

GL-Q01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Key takeaways

  • QScrollArea defaults to widgetResizable() == false (freezing inner layouts at initial size unless set true), and QStackedWidget::removeWidget(stub) requires explicit delete stub to free RAM.
  • Setting QLabel::setTextFormat(Qt::PlainText) on live bus strings prevents Qt::AutoText from misinterpreting < brackets in telemetry payloads as rich-text HTML tags.
  • QDockWidget and QMdiArea organize multi-pane engineering workbenches (saveState/restoreState), whereas QGraphicsView indexes thousands of zoomable 2D QGraphicsItem schematics via BSP trees.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets407/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Model/View vs Item-Widgets: QAbstractTableModel, QListView, QTreeView & Roles

free preview30 min

What you'll learn

  • Quantify why QTableWidget, QListWidget, and QTreeWidget stall at 50,000 records whereas QTableView, QListView, and QTreeView render visible viewports in O(visible) work.
  • Implement QAbstractTableModel::rowCount, columnCount, headerData, and role-guarded data() (Qt::DisplayRole, ForegroundRole, UserRole) over a flat C++20 std::vector.
  • Enforce flat-table parent.isValid() -> 0 bounds, unhandled-role QVariant{} returns, and QListView::setUniformItemSizes(true) optimizations.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets408/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Why Item-Based Convenience Widgets Hit a Memory and Latency Wall

  • Qt ships three pairs of data widgets that look deceptively similar: convenience item-widgets (QListWidget…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets409/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Why Item-Based Convenience Widgets Hit a Memory and Latency Wall

  • Do the arithmetic for a 50,000-row x 4-column industrial fault log: QTableWidget executes 200,000 s…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets410/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Why Item-Based Convenience Widgets Hit a Memory and Latency Wall

  • With QTableView + QAbstractTableModel (or QListView + QAbstractListModel), your C++ data stays once…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets411/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Why Item-Based Convenience Widgets Hit a Memory and Latency Wall

fig_m05_l02_a.svg

Figure 5.2a: Memory layout and GUI-thread latency comparison at 50,000 rows x 4 columns.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets412/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Mental model

note: QTableWidget on 50,000 fault rows is like printing and laminating 200,000 paper index cards before opening a 25-row inspection window; QAbstractTableModel keeps the binary ledger in one flat array and formats only the 25 rows currently visible behind the glass.

Where it stops working: Glass adds zero cost per glance, whereas QTableView calls data(index, role) several times per visible cell during every scroll repaint—so data() must stay fast, const, and free of blocking I/O.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets413/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

QModelIndex & Qt::ItemDataRole

definition: QModelIndex is a 24-byte (64-bit ABI) value locator combining row, column, a quintptr internalId/internalPointer (used by QAbstractItemModel / QTreeView hierarchies), and const QAbstractItemModel *. Qt::ItemDataRole (DisplayRole = 0, DecorationRole = 1, ForegroundRole = 9, CheckStateRole = 10, UserRole = 0x0100) selects which representation of that cell data() projects.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets414/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Why Item-Based Convenience Widgets Hit a Memory and Latency Wall

Avoid 200,000 individual heap item allocations by backing views directly with a contiguous std::vector<Record>.

Store records in std::vector<T>, serve visible cells via data(), and return {} else.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets415/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

QModelIndex Lifetimes, Qt::ItemDataRole Facets, and Tree vs Flat Contracts

  • QModelIndex is a tiny stack value (row(), column(), internalPointer(), model()), never a long-liv…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets416/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

QModelIndex Lifetimes, Qt::ItemDataRole Facets, and Tree vs Flat Contracts

  • Inside data(const QModelIndex &idx, int role), Qt::ItemDataRole cleanly separates presentation from typ…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets417/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

QModelIndex Lifetimes, Qt::ItemDataRole Facets, and Tree vs Flat Contracts

  • Finally, note how QTreeView generalizes tables and lists: every model method receives `const QModelIndex…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets418/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

QModelIndex Lifetimes, Qt::ItemDataRole Facets, and Tree vs Flat Contracts

fig_m05_l02_b.svg

Figure 5.2b: Mapping QListView, QTableView, and QTreeView onto QAbstractItemModel virtual contracts.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets419/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

telemetry_table_model.hpp

learner@ksa: ~/gl-q01/m05-l02
learner@ksa:~/gl-q01/m05-l02$ bat telemetry_table_model.hpp File: telemetry_table_model.hpp    #pragma once    #include <QAbstractTableModel>    #include <QColor>    #include <QHeaderView>    #include <QListView>    #include <QString>    #include <QTableView>    #include <QVariant>    #include <cstdint>    #include <vector>        struct TelemetrySample {        std::uint64_t timestampMs;        std::uint16_t channelId;
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets420/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

QAbstractTableModel-Roles

QAbstractTableModel-Roles(3qt) at a glance — GL-Q01
QAbstractTableModel-Roles(3qt) GL-Q01 Quick Reference QAbstractTableModel-Roles(3qt) NAME       QAbstractTableModel, QModelIndex, Qt::ItemDataRole - virtualized       Model/View contracts SYNOPSIS       int rowCount(const QModelIndex &p) const override { return p.isValid() ? 0 : m_rows.size(); }       QVariant data(const QModelIndex &i, int role = Qt::DisplayRole) const override;       listView->setUniformItemSizes(true);       tableView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); MANDATORY INVARIANTS       1. Return QVariant{} for every unhandled role (especially       Qt::CheckStateRole = 10). 2. Never cache transient QModelIndex values       across model mutations. 3. Expose typed domain integers via       Qt::UserRole + k rather than parsing DisplayRole strings. Kernel Systems Academy         m05-l02          QAbstractTableModel-Roles(3qt) GL-Q01 quick reference · full manual page: man 3qt QAbstractTableModel-Roles 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets421/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Host C++20 Benchmark Contrasting 50,000-Row Virtual Models vs Item Allocation

  • In verify.cpp, we populate 50,000 contiguous SampleRow structs (16 bytes each = 800 KiB) and meas…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets422/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Host C++20 Benchmark Contrasting 50,000-Row Virtual Models vs Item Allocation

  • Simultaneously, assertions verify row_count(valid_parent = true) == 0, !data(CheckState).valid, and typ…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets423/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m05-l02
learner@ksa:~/gl-q01/m05-l02$ bat verify.cpp File: verify.cpp    #include <algorithm>    #include <array>    #include <cassert>    #include <cstdint>    #include <cstdio>    #include <ctime>    #include <memory>    #include <string>    #include <vector>        enum class Role { Display, Foreground, CheckState, UserValue, UserSeverity };        struct Variant {        bool valid = false;
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets424/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Comparing O(visible) Viewport Latency Against Eager Item Allocation

  • Inspect the ./verify output: rows=50000 item_allocs=0 renders a 25-row (100-cell) viewport straight…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets425/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Comparing O(visible) Viewport Latency Against Eager Item Allocation

  • Next, Lesson 5.3 solves live mutation: appending new telemetry, evicting oldest ring entries, sorting and f…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets426/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Comparing O(visible) Viewport Latency Against Eager Item Allocation

learner@ksa: ~/gl-q01/m05-l02
learner@ksa:~/gl-q01/m05-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m05-l02./verifymodel_audit: rows=50000 item_allocs=0 vp25_p50_ns=15989 eager5k_alloc_ns=5646864learner@ksa:~/gl-q01/m05-l02
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets427/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Comparing O(visible) Viewport Latency Against Eager Item Allocation

strace — learner@ksa: ~/gl-q01/m05-l02
learner@ksa:~/gl-q01/m05-l02strace -e trace=write,exit_group ./verifywrite(1, "model_audit: rows=50000 item_all"..., 81) = 81exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets428/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Classic Custom Model Bugs: Phantom Checkboxes and ResizeToContents Freezes

  • Separating contiguous C++ backing storage from transient QModelIndex role queries scales QTableView, `Q…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets429/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Classic Custom Model Bugs: Phantom Checkboxes and ResizeToContents Freezes

  • Keep host-versus-target measurements scoped accurately: host CLOCK_MONOTONIC timings measure pure C++20 `…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets430/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Every cell across all four columns of QTableView renders an unwanted empty checkbox to the left of its text and bolds randomly. - Root Cause: QStyledItemDelegate queries Qt::CheckStateRole (10) and Qt::FontRole (6) on every cell; a non-null QString QVariant coerces to 0 (Qt::Unchecked). - Fix: Explicitly handle only intended roles (DisplayRole, ForegroundRole, UserRole + k) and return QVariant{} for all other roles.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets431/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Despite using QAbstractTableModel, opening the table freezes the HMI for 800 ms on startup and on every inserted row. - Root Cause: ResizeToContents forces the view to call data(DisplayRole) and measure font pixel width across all 50,000 rows instead of the 25 visible rows! - Fix: Use QHeaderView::Interactive or QHeaderView::Fixed/Stretch column modes and fixed vertical row heights on large models.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets432/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Guided Practice

  • Extend VirtualTelemetryModel in verify.cpp with a header_data(int section, Role role) method that ret…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets433/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Independent Practice

  • Implement a two-level hierarchical DeviceTreeModel in ISO C++20 (parent() and index() using integer n…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets434/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Quick check

Every cell in a custom QAbstractTableModel unexpectedly draws a checkbox beside its text even though Qt::ItemIsUserCheckable was never set. Why?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets435/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Quick check

Why must a flat QAbstractTableModel::rowCount(const QModelIndex &parent) return 0 whenever parent.isValid() is true?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets436/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Quick check

Which pair of view settings prevents O(N) full-model height scans when scrolling 50,000 rows in QListView and QTableView?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets437/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Summary

  • Convenience widgets (QTableWidget, QListWidget, QTreeWidget) allocate O(R * C) heap item objects and duplicate QVariant strings, whereas QTableView, QListView, and QTreeView query data() only for visible viewport cells.
  • QModelIndex is a transient stack coordinate (row, column, internalPointer, model *) that must never be cached across model insertions, removals, or resets.
  • QAbstractItemModel::data(index, role) projects multiple facets from one C++ struct (Qt::DisplayRole text, Qt::ForegroundRole color, Qt::UserRole + k raw typed integers) and must return empty QVariant{} for unhandled roles.
  • A flat QAbstractTableModel or QAbstractListModel must return 0 from rowCount(parent) whenever parent.isValid() is true, whereas QTreeView models encode parent-child pointers via createIndex(row, col, ptr).
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets438/570

GL-Q01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Key takeaways

  • QModelIndex is a transient stack coordinate (row, column, internalPointer, model *) that must never be cached across model insertions, removals, or resets.
  • QAbstractItemModel::data(index, role) projects multiple facets from one C++ struct (Qt::DisplayRole text, Qt::ForegroundRole color, Qt::UserRole + k raw typed integers) and must return empty QVariant{} for unhandled roles.
  • A flat QAbstractTableModel or QAbstractListModel must return 0 from rowCount(parent) whenever parent.isValid() is true, whereas QTreeView models encode parent-child pointers via createIndex(row, col, ptr).
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets439/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

beginInsertRows Contracts, QSortFilterProxyModel & Custom StyledItemDelegates

free preview35 minlab lab_m05_table_model_roles

What you'll learn

  • Bracket structural vector mutations inside inclusive beginInsertRows/endInsertRows and beginRemoveRows/endRemoveRows pairs so QPersistentModelIndex selections stay valid.
  • Filter and sort models zero-copy via QSortFilterProxyModel (beginFilterChange/endFilterChange, UserRole) while translating view indices with mapToSource.
  • Record reversible operator edits on QUndoStack/QUndoView and custom-paint cell badges in QStyledItemDelegate::paint without setIndexWidget bloat.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets440/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Structural Notification Contracts vs the beginResetModel Anti-Pattern

  • When live telemetry appends to m_rows at 20 Hz, calling beginResetModel(); endResetModel(); tells eve…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets441/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Structural Notification Contracts vs the beginResetModel Anti-Pattern

  • Two invariants in QAbstractItemModel are non-negotiable.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets442/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Structural Notification Contracts vs the beginResetModel Anti-Pattern

  • For non-structural edits—such as toggling an acknowledged flag on row r—do not touch insert/remove sign…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets443/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Structural Notification Contracts vs the beginResetModel Anti-Pattern

fig_m05_l03_a.svg

Figure 5.3a: Preserving selection, scroll position, and 60 Hz frame budgets on live filtered tables.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets444/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Mental model

note: Calling beginResetModel() every time one new alarm arrives is like ripping down an entire airport departures board and bolting up a fresh frame—beginInsertRows announces exact slot coordinates first so QTableView and QSortFilterProxyModel slide existing selection markers smoothly by +1.

Where it stops working: Mechanical split-flap boards tolerate an extra clack, whereas mutating m_rows BEFORE beginInsertRows() or passing half-open (N, N + 1) instead of inclusive (N, N) corrupts QSortFilterProxyModel's internal index vector and crashes the application.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets445/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

beginInsertRows Bracket & QSortFilterProxyModel

definition: beginInsertRows(parent, first, last) / endInsertRows() form a strict two-phase structural transaction on QAbstractItemModel: first and last are inclusive indices in the post-insert coordinate space (appending 1 row at size() == N passes (QModelIndex(), N, N)). QSortFilterProxyModel maintains bidirectional row/column permutation maps (mapToSource / mapFromSource) over a source model with zero data duplication.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets446/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Structural Notification Contracts vs the beginResetModel Anti-Pattern

Call beginInsertRows with inclusive [first, last] bounds BEFORE mutating m_rows, then call endInsertRows.

Call beginInsertRows(p,N,N) before push_back, mapToSource on clicks, and use delegates.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets447/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

QSortFilterProxyModel Coordinate Mapping, QUndoStack, and Flyweight Delegates

  • QSortFilterProxyModel wraps a source model to filter rows (filterAcceptsRow) and sort columns without c…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets448/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

QSortFilterProxyModel Coordinate Mapping, QUndoStack, and Flyweight Delegates

  • When operators acknowledge alarms or tune calibration cells inside a table, wrapping mutations in `QUndoCom…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets449/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

QSortFilterProxyModel Coordinate Mapping, QUndoStack, and Flyweight Delegates

  • Finally, resist calling tableView->setIndexWidget(idx, new QPushButton(...)) on large tables: 5,000 emb…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets450/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

QSortFilterProxyModel Coordinate Mapping, QUndoStack, and Flyweight Delegates

fig_m05_l03_b.svg

Figure 5.3b: Exact coordinate rules across QAbstractItemModel notifications, proxies, QUndoStack, and delegates.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets451/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

proxy_delegate_undo.cpp

learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03$ bat proxy_delegate_undo.cpp File: proxy_delegate_undo.cpp    #include <QAbstractTableModel>    #include <QPainter>    #include <QSortFilterProxyModel>    #include <QStyledItemDelegate>    #include <QUndoCommand>    #include <QUndoStack>    #include <vector>        struct AlarmEntry {        int id;        int severity; // 0=Info, 1=Warn, 2=Critical        bool acked = false;    };
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets452/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

QSortFilterProxyModel-QUndoStack

QSortFilterProxyModel-QUndoStack(3qt) at a glance — GL-Q01
QSortFilterProxyModel-QUndoStack(3qt) GL-Q01 Quick Reference QSortFilterProxyModel-QUndoStack(3qt) NAME       QSortFilterProxyModel, QStyledItemDelegate, QUndoStack - live proxy       mapping, delegates & undo SYNOPSIS       beginInsertRows(QModelIndex(), n, n); m_rows.push_back(x); endInsertRows();       const QModelIndex srcIdx = proxy->mapToSource(proxyIndex);       undoStack->push(new AckAlarmCommand(model, srcIdx.row()));       painter->save(); /* custom cell draw */ painter->restore(); CRITICAL RULES       1. [first, last] in beginInsertRows / beginRemoveRows is INCLUSIVE and       pre-mutation. 2. Never pass a proxy QModelIndex directly into       sourceModel methods without mapToSource(). 3. Use       QStyledItemDelegate::paint instead of setIndexWidget() on scrolling       tables. Kernel Systems Academy      m05-l03      QSortFilterProxyModel-QUndoStack(3qt) GL-Q01 quick reference · full manual page: man 3qt QSortFilterProxyModel-QUndoStack 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets453/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Host C++20 Verifier for Persistent Selection, Proxy Mapping, and Undo/Redo

  • In verify.cpp, we verify all three dynamic Model/View contracts together: PersistentIndex row shifting…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets454/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Host C++20 Verifier for Persistent Selection, Proxy Mapping, and Undo/Redo

  • Trace the sequence carefully: selecting row 1 (id = 102), prepending urgent id = 100 at row 0 shift…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets455/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03$ bat verify.cpp File: verify.cpp    #include <cassert>    #include <cstdio>    #include <memory>    #include <vector>        struct Alarm {        int id;        int sev;        bool acked = false;    };        class LiveStore {    public:        int track_persistent(int row) {
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets456/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Verifying Persistent Shifts, Proxy Coordinate Mapping, and Undo History

  • Confirm ./verify outputs proxy_undo_audit: crit_rows=2 mapped_src=2 redo_acked=1 evicted_handle=-1.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets457/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Verifying Persistent Shifts, Proxy Coordinate Mapping, and Undo History

  • Now put the complete bounded ring-buffer model, persistent selection shifter, and sort/filter proxy through…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets458/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Verifying Persistent Shifts, Proxy Coordinate Mapping, and Undo History

learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m05-l03./verifyproxy_undo_audit: crit_rows=2 mapped_src=2 redo_acked=1 evicted_handle=-1learner@ksa:~/gl-q01/m05-l03
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets459/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Verifying Persistent Shifts, Proxy Coordinate Mapping, and Undo History

strace — learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03strace -e trace=write,exit_group ./verifywrite(1, "proxy_undo_audit: crit_rows=2 ma"..., 74) = 74exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets460/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Proxy Row Mix-Ups, Painter State Leaks, and Half-Open Insert Bounds

  • Granular beginInsertRows/beginRemoveRows brackets, zero-copy QSortFilterProxyModel views, `QUndoStack…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets461/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Proxy Row Mix-Ups, Painter State Leaks, and Half-Open Insert Bounds

  • In Module 6, we complete GL-Q01 with crash-atomic QSaveFile configuration persistence, premultiplied ARGB…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets462/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Filtering a fault log to 'Critical Only' and clicking 'Clear Row' deletes an unrelated 'Info' record hidden at row 0 of the source vector. - Root Cause: View signals emit QModelIndex coordinates belonging to QSortFilterProxyModel, whose row 0 maps to an arbitrary source row. - Fix: Always call const QModelIndex srcIdx = proxy->mapToSource(proxyIdx); and check srcIdx.isValid() before touching source storage.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets463/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Every column to the right of column 2 renders with a thick red pen, no border, or clipped text. - Root Cause: QAbstractItemView passes one shared QPainter* across consecutive cells during paintEvent; un-restored brush/pen changes bleed into subsequent cells. - Fix: Call painter->save() before modifying pens, brushes, render hints, or clips, and pair with painter->restore() on every return path.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets464/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Guided Practice

  • Extend ProxyMap in verify.cpp with map_from_source(int src_row) returning the proxy row index (or `-1…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets465/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Independent Practice

  • Complete lab_m05_table_model_roles by fixing the three defects in starter/core.cpp: returning empty `Ro…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets466/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Quick check

m_rows currently holds 6 elements (indices 0..5). Which exact sequence validly appends 1 new record to a QAbstractTableModel?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets467/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Quick check

A QTableView is attached to SeverityProxy *proxy wrapping LiveAlarmModel *src. Inside connect(view, &QTableView::doubleClicked, ...), how do you locate the clicked AlarmEntry?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets468/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Quick check

Why is QStyledItemDelegate::paint vastly more scalable than QTableView::setIndexWidget() for rendering status pills in a 10,000-row table?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets469/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Lab: lab_m05_table_model_roles

  • Implement and verify a bounded-capacity FaultTableModel and FaultFilterProxy with multi-role data() d…

Verify: ./check.sh exits 0.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets470/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Summary

  • beginInsertRows(parent, first, last) and beginRemoveRows(parent, first, last) take inclusive [first, last] indices BEFORE mutating the backing vector, updating QPersistentModelIndex selections without resetting scroll state.
  • A view bound to QSortFilterProxyModel emits proxy QModelIndex coordinates that must be translated via proxy->mapToSource(proxyIdx) before indexing the source QAbstractItemModel.
  • QUndoStack and QUndoCommand (undo() / redo(), inspectable via QUndoView) encapsulate reversible operator table and parameter edits cleanly.
  • One flyweight QStyledItemDelegate::paint instance (painter->save() / restore()) custom-renders visible severity badges with zero extra QWidget allocations, unlike QAbstractItemView::setIndexWidget().
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets471/570

GL-Q01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Key takeaways

  • A view bound to QSortFilterProxyModel emits proxy QModelIndex coordinates that must be translated via proxy->mapToSource(proxyIdx) before indexing the source QAbstractItemModel.
  • QUndoStack and QUndoCommand (undo() / redo(), inspectable via QUndoView) encapsulate reversible operator table and parameter edits cleanly.
  • One flyweight QStyledItemDelegate::paint instance (painter->save() / restore()) custom-renders visible severity badges with zero extra QWidget allocations, unlike QAbstractItemView::setIndexWidget().
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets472/570

m06/

>_ Kernel Systems Academy

QSaveFile Persistence, QPainter/QtCharts & QTest CI

Persist HMI configuration crash-atomically via QSaveFile fsync-and-rename, composite premultiplied ARGB32 QPainter gauges and batched QtCharts waveforms, and automate headless offscreen QTest TAP 13 CI.

  1. 6.1 QFile, QTextStream & Crash-Atomic QSaveFile Configuration Persistence
  2. 6.2 Custom QPainter Gauges, Premultiplied ARGB32 & Real-Time QtCharts
  3. 6.3 Automated HMI Verification: QTest, QSignalSpy & Headless Offscreen TAP 13

lab → Lab 6 (Capstone): Atomic Calibration Store, ARGB32 Gauge Rasterizer & SignalSpy Harness

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets473/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

QFile, QTextStream & Crash-Atomic QSaveFile Configuration Persistence

free preview30 min

What you'll learn

  • Explain at the Linux kernel VFS syscall boundary why QFile (QIODevice::WriteOnly | QIODevice::Truncate) corrupts live files on power loss whereas QSaveFile stays atomic.
  • Trace the openat -> write -> fsync -> rename commit path of QSaveFile::commit() and the automatic unlink rollback of cancelWriting() and ~QSaveFile().
  • Serialize UTF-8 QTextStream (QStringConverter::Utf8) and QJsonDocument (QJsonParseError) payloads with all-or-nothing schema validation.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets474/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Why Truncate-in-Place Destroys Embedded Configurations on Power Loss

  • Field technicians shut down industrial machinery by throwing the main 24 V cabinet disconnect without cli…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets475/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Why Truncate-in-Place Destroys Embedded Configurations on Power Loss

  • If power drops two milliseconds later—or if ext4 delayed allocation has not yet flushed dirty page-cache…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets476/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Why Truncate-in-Place Destroys Embedded Configurations on Power Loss

  • QSaveFile eliminates that window completely.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets477/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Why Truncate-in-Place Destroys Embedded Configurations on Power Loss

fig_m06_l01_a.svg

Figure 6.1a: Linux kernel VFS syscall comparison between in-place QFile truncation and transactional QSaveFile.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets478/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Mental model

note: Overwriting calibration constants with QFile(WriteOnly | Truncate) is like wiping your shop's only reference whiteboard clean before copying new tolerances from a notebook; QSaveFile writes and verifies a second board first, then hangs it over the wall hooks in a single atomic swap.

Where it stops working: Hanging a physical board is immediately permanent, whereas POSIX rename() only updates the directory dentry atomically—the temporary file's data blocks MUST be flushed via fsync() before rename(), and newly created files also benefit from syncing the parent directory descriptor on ext4.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets479/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

QSaveFile Atomic Persistence Transaction

definition: QSaveFile subclasses QFileDevice (deliberately hiding close() as private) to enforce transactional POSIX file replacement. open(QIODevice::WriteOnly) creates a sibling .XXXXXX temporary file on the same mounted filesystem (preventing EXDEV cross-device rename errors), commit() executes fsync() + atomic rename(), and cancelWriting() aborts cleanly via unlink().

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets480/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Why Truncate-in-Place Destroys Embedded Configurations on Power Loss

Open QSaveFile at the target path so the temporary sibling resides on the same filesystem mount.

Ban QFile::Truncate on configs; write UTF-8 into QSaveFile, check errors, and commit().

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets481/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

QSaveFile::commit Internals, UTF-8 QTextStream, and QJsonDocument Validation

  • Notice a deliberate compile-time safeguard in QSaveFile: QSaveFile::close() is declared private!
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets482/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

QSaveFile::commit Internals, UTF-8 QTextStream, and QJsonDocument Validation

  • Pair QSaveFile with clean UTF-8 serializers.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets483/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

QSaveFile::commit Internals, UTF-8 QTextStream, and QJsonDocument Validation

  • For human-readable audit exports (CSV or INI), attach QTextStream stream(&saveFile).
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets484/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

QSaveFile::commit Internals, UTF-8 QTextStream, and QJsonDocument Validation

fig_m06_l01_b.svg

Figure 6.1b: Pairing Qt 6 I/O devices (QFile for reads, QSaveFile for writes) with UTF-8 serializers.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets485/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

atomic_config_persistence.cpp

learner@ksa: ~/gl-q01/m06-l01
learner@ksa:~/gl-q01/m06-l01$ bat atomic_config_persistence.cpp File: atomic_config_persistence.cpp    #include <QFile>    #include <QJsonDocument>    #include <QJsonObject>    #include <QJsonParseError>    #include <QSaveFile>    #include <QString>    #include <QStringConverter>    #include <QTextStream>        struct CalibrationConfig {        int zeroOffsetKpa = 0;        int alarmLimitKpa = 420;    };
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets486/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

QSaveFile-QTextStream

QSaveFile-QTextStream(3qt) at a glance — GL-Q01
QSaveFile-QTextStream(3qt)  GL-Q01 Quick Reference  QSaveFile-QTextStream(3qt) NAME       QSaveFile, QFile, QTextStream, QJsonDocument - crash-atomic Qt 6       configuration persistence SYNOPSIS       QSaveFile sf(targetPath);       if (!sf.open(QIODevice::WriteOnly)) return false;       if (sf.write(payload) != payload.size()) { sf.cancelWriting(); return false; }       return sf.commit();                     // close() is intentionally private!        DURABILITY & ROLLBACK INVARIANTS 1. Never open existing config files       with QFile(QIODevice::WriteOnly | QIODevice::Truncate). 2. Sibling temp       file stays in targetPath's directory so rename(2) never fails with       EXDEV. 3. Destroying QSaveFile without commit() automatically unlinks       the temporary file. Kernel Systems Academy           m06-l01            QSaveFile-QTextStream(3qt) GL-Q01 quick reference · full manual page: man 3qt QSaveFile-QTextStream 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets487/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Host C++20 Verifier Traced Under strace for Atomic Commit and Unlink Rollback

  • In verify.cpp, we build a POSIX AtomicSaveTransaction matching QSaveFile's exact syscall sequence (`o…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets488/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Host C++20 Verifier Traced Under strace for Atomic Commit and Unlink Rollback

  • Watch what happens across the two scopes in main(): scope 1 commits v1 (40 bytes) cleanly, while sc…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets489/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m06-l01
learner@ksa:~/gl-q01/m06-l01$ bat verify.cpp File: verify.cpp    #include <cassert>    #include <cstdio>    #include <cstdlib>    #include <fcntl.h>    #include <string>    #include <string_view>    #include <unistd.h>        class AtomicSaveTransaction {    public:        explicit AtomicSaveTransaction(std::string target)            : m_target(std::move(target)), m_tmp(m_target + ".tmp") {}            ~AtomicSaveTransaction() {
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets490/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Inspecting the Live Kernel strace Transcript of Commit and Rollback

  • Examine the strace capture below line by line!
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets491/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Inspecting the Live Kernel strace Transcript of Commit and Rollback

  • Immediately below it, Transaction 2 opens calib.json.tmp, writes "{\"corrupt_half", and calls `unlink…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets492/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Inspecting the Live Kernel strace Transcript of Commit and Rollback

learner@ksa: ~/gl-q01/m06-l01
learner@ksa:~/gl-q01/m06-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m06-l01./verifysavefile_audit: committed_bytes=41 rollback_intact=1 tmp_cleaned=1learner@ksa:~/gl-q01/m06-l01
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets493/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Inspecting the Live Kernel strace Transcript of Commit and Rollback

strace — learner@ksa: ~/gl-q01/m06-l01
learner@ksa:~/gl-q01/m06-l01strace -e \trace=openat,write,fsync,rename,renameat,renameat2,unlink,exit_group ./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libstdc++.so.6", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libgcc_s.so.1", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libm.so.6", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json.tmp", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0600) = 3write(3, "{\"schema_version\":1,\"zero\":-15,\""..., 41) = 41fsync(3)                                = 0rename("./.qsave_verify_KmSvV3/calib.json.tmp", "./.qsave_verify_KmSvV3/calib.json") = 0openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json.tmp", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0600) = 3write(3, "{\"corrupt_half", 14)         = 14unlink("./.qsave_verify_KmSvV3/calib.json.tmp") = 0
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets494/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Filesystem Mount Boundaries, Missing QTextStream Flushes, and Flash Wear

  • QSaveFile turns fragile configuration writes into crash-atomic transactions with five lines of C++20.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets495/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Filesystem Mount Boundaries, Missing QTextStream Flushes, and Flash Wear

  • Note the target storage boundary: fsync() durability depends on the underlying eMMC controller honoring…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets496/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Custom atomic-save helper works in desktop unit tests where everything is one root partition, then fails with EXDEV (Invalid cross-device link) on the embedded target. - Root Cause: Embedded rootfs layouts mount /tmp as a RAM-backed tmpfs, and POSIX rename() cannot move inodes across distinct filesystem mounts. - Fix: Use QSaveFile(targetPath), which always creates its temporary file in the exact same directory as targetPath.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets497/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Dragging a calibration slider stutters the GUI thread for tens of milliseconds per tick and accelerates eMMC NAND wear. - Root Cause: Each QSaveFile::commit() executes a synchronous blocking fsync() barrier down to flash storage. - Fix: Update RAM state live at 60 Hz, and trigger QSaveFile::commit() only on explicit 'Apply', dialog accept, or a debounced single-shot timer.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets498/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Guided Practice

  • Extend AtomicSaveTransaction::commit() in verify.cpp to also `openat(AT_FDCWD, parent_dir, O_RDONLY | O…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets499/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Independent Practice

  • Write a C++20 configuration loader with automatic .bak fallback that verifies a trailing CRC32 field in…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets500/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Quick check

A function opens QSaveFile sf("/var/lib/hmi/calib.json"), writes half a JSON object, and returns early on an error without calling sf.commit(). What is left on disk?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets501/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Quick check

Why does QSaveFile create its temporary file in the same directory as the destination path instead of /tmp?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets502/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Quick check

Why does calling sf.close() on a QSaveFile instance fail to compile in Qt 6?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets503/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Summary

  • Opening an existing configuration file with QFile and QIODevice::WriteOnly | QIODevice::Truncate zeroes the live inode immediately (O_TRUNC), leaving a 0-byte or partial file if power fails mid-write.
  • QSaveFile writes to a sibling temporary file in the destination directory, flushes storage via fsync(), and atomically replaces the target via POSIX rename() inside commit().
  • If QSaveFile leaves scope without calling commit() (or after cancelWriting()), ~QSaveFile() closes and unlink()s the temporary file while leaving the previous configuration file untouched.
  • Qt 6 QTextStream defaults to QStringConverter::Utf8 (requiring explicit status() == QTextStream::Ok checks), while QJsonDocument::fromJson pinpoints syntax faults via QJsonParseError.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets504/570

GL-Q01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Key takeaways

  • QSaveFile writes to a sibling temporary file in the destination directory, flushes storage via fsync(), and atomically replaces the target via POSIX rename() inside commit().
  • If QSaveFile leaves scope without calling commit() (or after cancelWriting()), ~QSaveFile() closes and unlink()s the temporary file while leaving the previous configuration file untouched.
  • Qt 6 QTextStream defaults to QStringConverter::Utf8 (requiring explicit status() == QTextStream::Ok checks), while QJsonDocument::fromJson pinpoints syntax faults via QJsonParseError.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets505/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Custom QPainter Gauges, Premultiplied ARGB32 & Real-Time QtCharts

free preview35 min

What you'll learn

  • Implement custom QWidget::paintEvent(QPaintEvent *) gauges using logical translate/scale transforms, ev->region() clipping, and update() coalescing.
  • Prove Porter-Duff SourceOver compositing arithmetic on QImage::Format_ARGB32_Premultiplied static dial caches without per-pixel alpha division.
  • Eliminate GUI-thread stalls in real-time QtCharts (QChart, QLineSeries, QValueAxis) by replacing per-sample append() calls with ring-buffered replace(QList<QPointF>).
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets506/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Premultiplied Alpha Physics and the paintEvent Backing-Store Contract

  • In QtWidgets, every top-level window owns a software double-buffered backing store managed by `QWidgetRep…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets507/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Premultiplied Alpha Physics and the paintEvent Backing-Store Contract

  • When caching static bezel rings and tick marks into an off-screen QImage, always choose `QImage::Format_A…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets508/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Premultiplied Alpha Physics and the paintEvent Backing-Store Contract

  • Inside paintEvent, normalize DPI and resize math by translating (width()/2.0, height()/2.0) and scaling…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets509/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Premultiplied Alpha Physics and the paintEvent Backing-Store Contract

fig_m06_l02_a.svg

Figure 6.2a: Eliminating per-pixel division and per-sample chart re-layout on embedded Linux HMIs.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets510/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Mental model

note: Caching static gauge ticks into a Format_ARGB32_Premultiplied QImage and batching QLineSeries::replace() works like printing an oscilloscope's graticule grid onto the glass bezel once and sweeping one complete phosphor trace per frame—instead of re-engraving the glass ruler every millisecond a sample arrives.

Where it stops working: Etched glass consumes zero RAM, whereas each cached 400x400 ARGB32_Premultiplied QImage occupies 640 KiB (400 * 400 * 4 bytes)—so cache shared dial backgrounds per distinct size rather than duplicating hundreds of megapixel bitmaps.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets511/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Premultiplied ARGB32 & QLineSeries::replace()

definition: In QImage::Format_ARGB32_Premultiplied, a pixel with straight color (A, R, G, B) stores (A, R*A/255, G*A/255, B*A/255) (invariant R', G', B' <= A), matching Qt's software rasterizer natively with zero format conversion or alpha division. In QtCharts, QXYSeries::replace(const QList<QPointF> &) swaps the entire vertex vector and emits a single pointsReplaced() notification instead of N pointAdded(int) signals.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets512/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Premultiplied Alpha Physics and the paintEvent Backing-Store Contract

Guard setters for value changes and call asynchronous update() so Qt coalesces dirty regions.

Paint in paintEvent via update(), cache ARGB32_Premultiplied, and batch series->replace().

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets513/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

High-Rate Real-Time Waveforms in QtCharts: Why replace Beats append

  • Alongside radial gauges, industrial HMIs plot rolling 512-sample pressure and current waveforms using `Qt…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets514/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

High-Rate Real-Time Waveforms in QtCharts: Why replace Beats append

  • Every single append(x, y) emits pointAdded(int), marks the QGraphicsScene dirty, and triggers chart g…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets515/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

High-Rate Real-Time Waveforms in QtCharts: Why replace Beats append

  • Pair replace() with three QChart hardening settings: call `chart->setAnimationOptions(QChart::NoAnimati…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets516/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

High-Rate Real-Time Waveforms in QtCharts: Why replace Beats append

fig_m06_l02_b.svg

Figure 6.2b: Bit-level premultiplied ARGB32 layout and QtCharts real-time series architecture.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets517/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

gauge_and_chart_panel.cpp

learner@ksa: ~/gl-q01/m06-l02
learner@ksa:~/gl-q01/m06-l02$ bat gauge_and_chart_panel.cpp File: gauge_and_chart_panel.cpp    #include <QtCharts/QChart>    #include <QtCharts/QChartView>    #include <QtCharts/QLineSeries>    #include <QtCharts/QValueAxis>    #include <QHBoxLayout>    #include <QImage>    #include <QList>    #include <QPaintEvent>    #include <QPainter>    #include <QPointF>    #include <QWidget>    #include <algorithm>        class RadialPressureGauge final : public QWidget {
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets518/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

QPainter-QtCharts

QPainter-QtCharts(3qt) at a glance — GL-Q01
QPainter-QtCharts(3qt)      GL-Q01 Quick Reference      QPainter-QtCharts(3qt) NAME       QPainter, QImage::Format_ARGB32_Premultiplied, QLineSeries - 60 Hz       gauges & batched charts SYNOPSIS       QImage cache(size(), QImage::Format_ARGB32_Premultiplied);       cache.fill(Qt::transparent);       painter.setClipRegion(event->region());       painter.drawArc(rectF, startDeg * 16, spanDeg * 16);       lineSeries->replace(framePointsList);   // 1 signal per frame vs N append() signals        PERFORMANCE & CORRECTNESS RULES 1. Paint QWidgets ONLY inside       paintEvent(QPaintEvent *); trigger redraws via update(). 2.       Premultiplied ARGB32 requires R', G', B' <= A; clear new QImages before       drawing. 3. Set QChart::NoAnimation and batch streaming waveforms via       QXYSeries::replace(). Kernel Systems Academy             m06-l02              QPainter-QtCharts(3qt) GL-Q01 quick reference · full manual page: man 3qt QPainter-QtCharts 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets519/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Host C++20 Verifier & Benchmark for Premultiplied ARGB32 and Batched Series Replace

  • In verify.cpp, we verify three exact quantitative mechanisms: premultiplied ARGB32 Porter-Duff `SourceOve…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets520/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Host C++20 Verifier & Benchmark for Premultiplied ARGB32 and Batched Series Replace

  • Check both pixel invariants and notification counts: pixels outside the dirty clip remain 0xFF102030, ble…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets521/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m06-l02
learner@ksa:~/gl-q01/m06-l02$ bat verify.cpp File: verify.cpp    #include <algorithm>    #include <array>    #include <cassert>    #include <cmath>    #include <cstdint>    #include <cstdio>    #include <ctime>    #include <numbers>    #include <vector>        struct Rect {        int x, y, w, h;        constexpr bool contains(int px, int py) const noexcept {            return px >= x && px < (x + w) && py >= y && py < (y + h);
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets522/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Verifying ARGB32 Blending, Clip Isolation, and QtCharts Batch Speedup

  • Confirm ./verify outputs inside=0xFF772326 clipped=0xFF102030 tip=(50,15) along with append_ns more t…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets523/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Verifying ARGB32 Blending, Clip Isolation, and QtCharts Batch Speedup

  • Next, Lesson 6.3 automates verification of custom gauges, signals, and interactive widgets inside headless…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets524/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Verifying ARGB32 Blending, Clip Isolation, and QtCharts Batch Speedup

learner@ksa: ~/gl-q01/m06-l02
learner@ksa:~/gl-q01/m06-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m06-l02./verifyrender_audit: inside=0xFF76232B clipped=0xFF102030 tip=(50,15) append_ns=1122140 replace_ns=16678learner@ksa:~/gl-q01/m06-l02
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets525/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Verifying ARGB32 Blending, Clip Isolation, and QtCharts Batch Speedup

strace — learner@ksa: ~/gl-q01/m06-l02
learner@ksa:~/gl-q01/m06-l02strace -e trace=write,exit_group ./verifywrite(1, "render_audit: inside=0xFF76232B "..., 98) = 98exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets526/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Uninitialized QImage Garbage, 1/16th-Degree Arc Bugs, and Chart Animations

  • Premultiplied ARGB32 static layer caching and ring-buffered QLineSeries::replace() allow CPU-rendered `Qt…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets527/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Uninitialized QImage Garbage, 1/16th-Degree Arc Bugs, and Chart Animations

  • Remember the hardware boundary: host benchmarks prove compositing and batching complexity, whereas display…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets528/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Custom gauge renders random colored static noise and corrupted text streaks behind the dial arc on startup and resize. - Root Cause: QImage(size, format) allocates an uninitialized heap pixel buffer containing leftover allocator bytes. - Fix: Call image.fill(Qt::transparent) (0x00000000 in premultiplied ARGB32) immediately before opening QPainter(&image).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets529/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Gauge arc intended to sweep 240 degrees renders as a tiny 15-degree tick mark near 3 o'clock. - Root Cause: QPainter::drawArc, drawPie, and drawChord expect integer angles in 1/16th-degree increments (5760 == 360 deg). - Fix: Multiply both startAngle and spanAngle by 16 (e.g., 210 * 16 and -240 * 16 for a clockwise 240-degree sweep).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets530/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Guided Practice

  • Add a channel-invariant verifier is_valid_premul(uint32_t px) to verify.cpp checking that pr <= a, `p…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets531/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Independent Practice

  • Write a fixed-capacity power-of-two WaveformRing<512> in C++20 supporting push_isr_sample(float) and `c…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets532/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Quick check

Why does Qt's raster paint engine strongly prefer QImage::Format_ARGB32_Premultiplied over straight QImage::Format_ARGB32 for off-screen QPainter caches?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets533/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Quick check

What does painter.drawArc(rect, 90, 180) actually draw on screen?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets534/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Quick check

A 1 kHz ADC stream feeds a QtCharts QLineSeries strip chart on an embedded panel, pegging CPU usage at 100%. Which change fixes the bottleneck?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets535/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Summary

  • All QWidget drawing must execute inside paintEvent(QPaintEvent *) (scheduled asynchronously via update()), honoring event->region() dirty clip bounds on the window backing store.
  • QImage::Format_ARGB32_Premultiplied pre-scales RGB channels by alpha / 255, letting QPainter Porter-Duff SourceOver blend out = src + dst * (255 - a) / 255 without per-pixel division.
  • Caching static gauge bezels and tick marks into a Format_ARGB32_Premultiplied QImage on resizeEvent avoids repeating trigonometric tick strokes on every 60 Hz needle update.
  • In QtCharts, calling QLineSeries::append(x, y) at 1 kHz triggers 1,000 per-point signal/layout passes per second, whereas buffering samples and calling series->replace(points) at 30 Hz emits once per frame.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets536/570

GL-Q01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Key takeaways

  • QImage::Format_ARGB32_Premultiplied pre-scales RGB channels by alpha / 255, letting QPainter Porter-Duff SourceOver blend out = src + dst * (255 - a) / 255 without per-pixel division.
  • Caching static gauge bezels and tick marks into a Format_ARGB32_Premultiplied QImage on resizeEvent avoids repeating trigonometric tick strokes on every 60 Hz needle update.
  • In QtCharts, calling QLineSeries::append(x, y) at 1 kHz triggers 1,000 per-point signal/layout passes per second, whereas buffering samples and calling series->replace(points) at 30 Hz emits once per frame.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets537/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Automated HMI Verification: QTest, QSignalSpy & Headless Offscreen TAP 13

free preview30 minlab lab_m06_qpainter_gauge_qtest

What you'll learn

  • Drive interactive widgets headlessly under QT_QPA_PLATFORM=offscreen using QTest::mouseClick, QTest::keyClicks, and data-driven _data() / QFETCH tables.
  • Verify exact signal emission counts, argument payloads, and asynchronous timer slots using QSignalSpy and spy.wait() / QTRY_COMPARE instead of blocking sleep.
  • Emit machine-parsable TAP version 13 test transcripts via -o -,tap for automated CI gating.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets538/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Headless Offscreen QPA Execution and Why Thread Sleeps Starve QTimers

  • Many embedded teams skip automated GUI testing because they assume QtWidgets binaries require an X11 or…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets539/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Headless Offscreen QPA Execution and Why Thread Sleeps Starve QTimers

  • When testing asynchronous HMI behavior—such as a 20 ms debounce QTimer after an operator clicks Arm—e…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets540/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Headless Offscreen QPA Execution and Why Thread Sleeps Starve QTimers

  • QSignalSpy::wait(200) and QTRY_COMPARE(spy.count(), 1) spin a nested QEventLoop until the signal arri…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets541/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Headless Offscreen QPA Execution and Why Thread Sleeps Starve QTimers

fig_m06_l03_a.svg

Figure 6.3a: End-to-end headless QtWidgets verification from synthetic input injection to TAP 13 CI gates.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets542/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Mental model

note: QTest + QSignalSpy under QT_QPA_PLATFORM=offscreen is an automated pneumatic fixture jig for your HMI: mechanical solenoids tap Arm, Start, and E-Stop across dozens of fault combinations in milliseconds while digital logic analyzers count exact output pulses into a TAP 13 test report.

Where it stops working: Headless offscreen proves C++20 state machines, QLayout geometry, QSignalSpy payloads, and software QPainter pixels, whereas physical DRM/KMS VSync tear, capacitive touch EMI noise, and optical sunlight contrast still require target hardware bench sign-off.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets543/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

QSignalSpy & Offscreen QPA Plugin

definition: Qt Platform Abstraction (QPA) decouples QtGui/QtWidgets from windowing systems; the built-in offscreen QPA plugin backs windows with RAM QImage surfaces so CI containers need zero display servers. QSignalSpy attaches dynamically via QMetaObject (inheriting QList<QList<QVariant>>) to capture every signal emission and pump QEventLoop inside wait(timeoutMs).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets544/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Headless Offscreen QPA Execution and Why Thread Sleeps Starve QTimers

Export QT_QPA_PLATFORM=offscreen and pass -o -,tap so headless CI runners parse TAP version 13 output.

Run QT_QPA_PLATFORM=offscreen ./tst -o -,tap with _data(), mouseClick, and spy.wait().

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets545/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Data-Driven _data Matrices, Synthetic Input Injection, and TAP 13 CI Gates

  • Qt6::Test pairs private test slots (void interlockMatrix()) with companion data-generator slots (`void…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets546/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Data-Driven _data Matrices, Synthetic Input Injection, and TAP 13 CI Gates

  • Rather than calling internal helper methods directly, drive widgets through their public user surface with…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets547/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Data-Driven _data Matrices, Synthetic Input Injection, and TAP 13 CI Gates

  • Pass -o -,tap on the CI command line so QTest emits TAP version 13 (`ok 1 - interlockMatrix(below_lim…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets548/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Data-Driven _data Matrices, Synthetic Input Injection, and TAP 13 CI Gates

fig_m06_l03_b.svg

Figure 6.3b: Core Qt6::Test primitives for deterministic widget, signal, timer, and pixel regression suites.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets549/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

tst_hmi_panel.cpp

learner@ksa: ~/gl-q01/m06-l03
learner@ksa:~/gl-q01/m06-l03$ bat tst_hmi_panel.cpp File: tst_hmi_panel.cpp    #include <QLineEdit>    #include <QPushButton>    #include <QSignalSpy>    #include <QTimer>    #include <QtTest>        class DebouncedSetpointBox final : public QWidget {        Q_OBJECT    public:        explicit DebouncedSetpointBox(QWidget *parent = nullptr) : QWidget(parent) {            m_edit = new QLineEdit(this);            m_applyBtn = new QPushButton(tr("Apply"), this);            m_applyBtn->setMinimumSize(44, 44);            m_applyBtn->setAutoRepeat(false);
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets550/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

QTest-QSignalSpy

QTest-QSignalSpy(3qt) at a glance — GL-Q01
QTest-QSignalSpy(3qt)       GL-Q01 Quick Reference       QTest-QSignalSpy(3qt) NAME       QTest, QSignalSpy, QTRY_COMPARE - headless QtWidgets input simulation &       TAP 13 CI SYNOPSIS       QT_QPA_PLATFORM=offscreen ./tst_hmi_panel -o -,tap       QSignalSpy spy(&widget, &Widget::alarmCrossed);       QTest::keyClicks(lineEdit, "425");       QTest::mouseClick(applyBtn, Qt::LeftButton);       QVERIFY(spy.wait(200));                 // pumps QEventLoop; NEVER use sleep_for()! CI VERIFICATION RULES       1. Pair private slot foo() with foo_data() + QFETCH for table-driven       edge cases. 2. Assert spy.count() and spy.at(0).at(0) payloads on       rising-edge hysteresis transitions. 3. Include "tst_file.moc" when       defining Q_OBJECT test classes inside a .cpp translation unit. Kernel Systems Academy              m06-l03              QTest-QSignalSpy(3qt) GL-Q01 quick reference · full manual page: man 3qt QTest-QSignalSpy 
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets551/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Host C++20 Verifier for Event-Pumping SignalSpy::wait, Input Clicks, and Data Rows

  • In verify.cpp, we construct a C++20 MiniEventLoop, a DebouncedPanel scheduling asynchronous 15 ms c…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets552/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Host C++20 Verifier for Event-Pumping SignalSpy::wait, Input Clicks, and Data Rows

  • Notice how verify.cpp also proves the thread-sleep anti-pattern directly: advancing wall wait WITHOUT pum…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets553/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

verify.cpp

learner@ksa: ~/gl-q01/m06-l03
learner@ksa:~/gl-q01/m06-l03$ bat verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cstdio>    #include <functional>    #include <string>    #include <tuple>    #include <vector>        class MiniEventLoop {    public:        void single_shot(int delay_ms, std::function<void()> cb) {            m_timers.push_back({m_now_ms + delay_ms, std::move(cb)});        }        void step_ms(int dt_ms) {
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets554/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Verifying Data-Driven Hysteresis Rows and Event-Pumping SignalSpy Output

  • Confirm ./verify prints qtest_audit: tap_rows=4/4 spy_wait_pumped=1 platform=offscreen.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets555/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Verifying Data-Driven Hysteresis Rows and Event-Pumping SignalSpy Output

  • You are ready for the Module 6 Capstone Studio lab_m06_qpainter_gauge_qtest, uniting crash-atomic calibra…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets556/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Verifying Data-Driven Hysteresis Rows and Event-Pumping SignalSpy Output

learner@ksa: ~/gl-q01/m06-l03
learner@ksa:~/gl-q01/m06-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m06-l03./verifyqtest_audit: tap_rows=4/4 spy_wait_pumped=1 platform=offscreenlearner@ksa:~/gl-q01/m06-l03
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets557/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Verifying Data-Driven Hysteresis Rows and Event-Pumping SignalSpy Output

strace — learner@ksa: ~/gl-q01/m06-l03
learner@ksa:~/gl-q01/m06-l03strace -e trace=write,exit_group ./verifywrite(1, "qtest_audit: tap_rows=4/4 spy_wa"..., 63) = 63exit_group(0)                           = ?+++ exited with 0 +++
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets558/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

CI Test Flakiness: Sleeping the GUI Thread and Missing Local .moc Includes

  • Across the six modules of GL-Q01, you have built a complete engineering foundation in ISO C++20 and Qt 6.…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets559/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

CI Test Flakiness: Sleeping the GUI Thread and Missing Local .moc Includes

  • Next in the series, GL-Q02 (linux-qt-io-concurrency) scales your HMIs across QThread worker pipelines…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets560/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: QTimer::singleShot and queued signals never fire during the sleep, causing QCOMPARE(spy.count(), 1) to fail 100% of the time. - Root Cause: QTest slots execute on the main thread; sleeping that thread halts QEventDispatcher so timers and posted events cannot run. - Fix: Replace thread sleeps with QVERIFY(spy.wait(timeoutMs)), QTRY_COMPARE(expr, expected), or QTest::qWait().

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets561/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Linker fails with 'undefined reference to vtable for TestHmiPanel' or QTest executes 0 private test slots. - Root Cause: CMAKE_AUTOMOC generates tst_panel.moc for Q_OBJECT classes declared inside a .cpp file rather than compiling a separate mocs_compilation entry. - Fix: Place #include "tst_panel.moc" at the very bottom of tst_panel.cpp right after QTEST_MAIN(TestHmiPanel).

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets562/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Guided Practice

  • Add a fifth row "invalid_out_of_range" (inputs = {"999", "50"}) to rows in verify.cpp where `mouse_…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets563/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Independent Practice

  • Complete the GL-Q01 Capstone Project (lab_m06_qpainter_gauge_qtest) by repairing the three starter defe…
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets564/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Quick check

Which command runs a compiled QtWidgets QTest binary inside a headless Linux CI container without X11/Wayland and prints TAP version 13 results to stdout?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets565/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Quick check

Inside a QTest test slot, why does std::this_thread::sleep_for(100ms) prevent a 15 ms QTimer::singleShot from firing before the next QCOMPARE?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets566/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Quick check

Why is driving a test via QTest::mouseClick(applyBtn, Qt::LeftButton) stronger than calling panel.applySetpoint(420) directly?

Select an option or press R to reveal.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets567/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Lab: lab_m06_qpainter_gauge_qtest

  • Integrate and verify an end-to-end C++20 HMI Gauge Capstone uniting QSaveFile-style fsync + rename ca…

Verify: ./check.sh exits 0.

GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets568/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Summary

  • Setting QT_QPA_PLATFORM=offscreen runs full QtWidgets layouts, input dispatch, and QPainter grab() rasterization in headless Linux CI containers without X11 or Wayland.
  • QTest::mouseClick and QTest::keyClicks synthesize realistic user events through QWidget event filters and button interlocks, paired with _data() / QFETCH boundary matrices.
  • QSignalSpy records emitted signal argument lists (spy.count(), spy.at(i)), while spy.wait() and QTRY_COMPARE pump the thread event loop instead of deadlocking timers with sleep.
  • Passing -o -,tap to a compiled QTest binary formats stdout as standard TAP version 13 (ok / not ok + YAML diagnostics) for CI pipelines.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets569/570

GL-Q01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Key takeaways

  • QTest::mouseClick and QTest::keyClicks synthesize realistic user events through QWidget event filters and button interlocks, paired with _data() / QFETCH boundary matrices.
  • QSignalSpy records emitted signal argument lists (spy.count(), spy.at(i)), while spy.wait() and QTRY_COMPARE pump the thread event loop instead of deadlocking timers with sleep.
  • Passing -o -,tap to a compiled QTest binary formats stdout as standard TAP version 13 (ok / not ok + YAML diagnostics) for CI pipelines.
GL-Q01 · Modern C++20 Foundations, QObject Meta-Object Internals & Qt 6 Widgets570/570

slides — overview

cover

m01/ C++20 Toolchain, RAII Lifetimes & QObject Ownership Trees

m02/ Qt 6 PIMPL ABI, Designer uic Forms & moc Meta-Object Tables

m03/ PMF Signal Lifetimes, Event Filters & Monotonic Timers

m04/ Button Interlocks, Input Validators & Geometry Layout Solvers

m05/ Container Widgets, QAbstractItemModel Roles & Proxy Views

m06/ QSaveFile Persistence, QPainter/QtCharts & QTest CI

search — fzf

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

keyboard shortcuts — less

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

figure