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.
- 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
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 ISO C++20 Flags, CMake AUTOMOC & Translation-Unit Hygiene
- 1.2 RAII, Rule of Five & QObject Parent-Child Ownership Trees
- 1.3 Virtual Dispatch, Inheritance, Operator Overloads & C++20 Concepts
lab → C++20 RAII Move Guards, Intrusive QObject Tree Cycles & deleteLater Sweep
GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# ISO C++20 Flags, CMake AUTOMOC & Translation-Unit Hygiene
What you'll learn
- Configure target-scoped CMake 3.28+ properties enforcing strict ISO C++20 without GNU extensions alongside
AUTOMOC,AUTOUIC, andAUTORCC. - Diagnose missing
vtablelinker errors triggered whenQ_OBJECTclasses live privately inside.cppfiles or outsideAUTOMOCtarget sources. - Quantify preprocessor and incremental rebuild fan-out reductions achieved by replacing
<QtWidgets>umbrella includes with forward declarations.
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 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Legacy Global Build Macros Break Incremental Qt 6 Builds
- Before
g++compiles anyQObjecttranslation unit, three code generators execute inside the build graph.
GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Legacy Global Build Macros Break Incremental Qt 6 Builds
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 · 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 · 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 · 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 · 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 createsksa_hmi_autogen/include/for generated head…
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 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Inside Autogen Artifact Layout and Header Dependency Fan-Out
Figure 1.1b: Separating header moc compilation, inline .moc includes, ui_*.h forms, and qrc_*.cpp arrays prevents mystery link errors.
GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# CMakeLists.txt
learner@ksa:~/gl-q01/m01-l01$ bat CMakeLists.txt───────┬──────────────────────────────────────────────────────────────────────────────── │ File: CMakeLists.txt───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ cmake_minimum_required(VERSION 3.28) 2 │ project(ksa_hmi VERSION 1.0.0 LANGUAGES CXX) 3 │ 4 │ find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets Test) 5 │ 6 │ add_executable(ksa_hmi 7 │ src/main.cpp 8 │ src/panel_window.hpp 9 │ src/panel_window.cpp 10 │ src/panel_window.ui 11 │ resources/icons.qrc 12 │ ) 13 │ 14 │ set_target_properties(ksa_hmi PROPERTIES───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# cmake-qt
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 · 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 · 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 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m01-l01$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <cassert> 2 │ #include <cstdio> 3 │ #include <string> 4 │ #include <string_view> 5 │ #include <vector> 6 │ 7 │ namespace hmi_build { 8 │ 9 │ struct SourceUnit { 10 │ std::string path; 11 │ bool has_q_object; 12 │ bool has_dot_moc_include; 13 │ bool pulls_umbrella_qtwidgets; 14 │ int client_tus;───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Inspecting Autogen Audit Metrics and System Call Output
- Confirm that
./verifyprintsclean(hdr=2 inline=1 err=0 kloc=84)versus `broken(err=1 umbrella=2 kloc=1…
GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Inspecting Autogen Audit Metrics and System Call Output
- Inspect the
straceoutput below as well: the compiled C++20 binary flushes its formatted summary in one `…
GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Inspecting Autogen Audit Metrics and System Call Output
learner@ksa:~/gl-q01/m01-l01$ g++ -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 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Inspecting Autogen Audit Metrics and System Call Output
learner@ksa:~/gl-q01/m01-l01$ strace -e trace=write,exit_group ./verifywrite(1, "AUTOMOC clean(hdr=2 inline=1 err"..., 79) = 79exit_group(0) = ?+++ exited with 0 +++GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Build-Graph and Meta-Object Linker Pitfalls
- Whenever
ldfails withundefined reference to vtable for MyWidgetor `undefined reference to MyWidget::…
GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Build-Graph and Meta-Object Linker Pitfalls
- With strict
-std=c++20,PRIVATEwarning flags, importedQt6::*targets, and forward-declared headers…
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 · 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 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Guided Practice
- Extend
SourceUnitinverify.cppwith a booleanin_target_sourcesfield and verify what happens when a…
GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Independent Practice
- Audit an existing C++ or
qmake.proHMI directory layout and draft a cleanCMakeLists.txtsplitting p…
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.
Correct: B
Because PollWorker exists only inside poller.cpp, mocs_compilation.cpp cannot see its declaration; #include "poller.moc" compiles the generated meta-object methods in scope.
Common misconception: Assuming mocs_compilation.cpp has visibility into private classes declared inside .cpp files.
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.
Correct: A
Storing QPushButton * requires only sizeof(void *); moving #include <QPushButton> to panel_window.cpp shields every other translation unit from widget header fan-out.
Common misconception: Confusing complete-type requirements of by-value members with fixed-width pointer members.
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.
Correct: D
CXX_STANDARD_REQUIRED ON prevents silent standard downgrade and CXX_EXTENSIONS OFF selects -std=c++20 instead of -std=gnu++20.
Common misconception: Believing CXX_STANDARD 20 alone disables GNU extensions or forbids fallback to C++17.
GL-Q01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Summary
- Enabling
CMAKE_AUTOMOC,CMAKE_AUTOUIC, andCMAKE_AUTORCCas target properties schedulesmoc,uic, andrccin the CMake build graph automatically whenever headers,.uiforms, or.qrcmanifests change. - Linking imported targets such as
Qt6::Widgetsviatarget_link_librariespropagates transitive include paths, compile definitions, and-fPICflags without polluting unrelated targets like legacy.proglobals. - Declaring a private
Q_OBJECTsubclass directly insideworker.cpprequires#include "worker.moc"at the bottom ofworker.cppbecausemocs_compilation.cppcannot 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 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Key takeaways
- Linking imported targets such as
Qt6::Widgetsviatarget_link_librariespropagates transitive include paths, compile definitions, and-fPICflags without polluting unrelated targets like legacy.proglobals. - Declaring a private
Q_OBJECTsubclass directly insideworker.cpprequires#include "worker.moc"at the bottom ofworker.cppbecausemocs_compilation.cppcannot 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 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# RAII, Rule of Five & QObject Parent-Child Ownership Trees
What you'll learn
- Implement a
noexceptRule-of-Five RAII guard innamespace hmiusingstd::exchangeand self-move protection for non-QObjectkernel handles. - Trace exact C++ destructor ordering across derived members, base
~QObject(), and intrusive child widget lists. - Eliminate heap corruption caused by stack-allocated child
QObjectordering errors or dualstd::unique_ptr+QObjectparenting.
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 · 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_ptrwithQObjectparenting…
GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Two Competing Lifetime Models Inside One C++20 Binary
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 · 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 · 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 · 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 · 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::AlarmBannerinpanel_owner.cppbelow.
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_statusinitialized…
GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Destructor Execution Sequence Across Derived Members and QObjectPrivate
Figure 1.2b: Derived members unwind before ~QObject(), explaining why raw child pointers pair cleanly with parent-owned heap widgets.
GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# panel_owner.cpp
learner@ksa:~/gl-q01/m01-l02$ bat panel_owner.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: panel_owner.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QLabel> 2 │ #include <QPushButton> 3 │ #include <QVBoxLayout> 4 │ #include <QWidget> 5 │ #include <unistd.h> 6 │ #include <utility> 7 │ 8 │ namespace hmi { 9 │ 10 │ class FdGuard { 11 │ public: 12 │ explicit FdGuard(int fd = -1) noexcept : m_fd(fd) {} 13 │ ~FdGuard() { reset(); }───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# QObject-ownership
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 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Proving RAII Move Semantics and Tree Unwinding in Host C++20
- In
verify.cpp, we buildhmi::MoveHandleand an intrusivehmi::ObjectNodetree in strict ISO C++20 to…
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: poppingchildfromm_childrenand setting `child->m_parent = nullptr…
GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m01-l02$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <algorithm> 2 │ #include <cassert> 3 │ #include <cstdio> 4 │ #include <memory> 5 │ #include <string> 6 │ #include <utility> 7 │ #include <vector> 8 │ 9 │ namespace hmi { 10 │ 11 │ class MoveHandle { 12 │ public: 13 │ MoveHandle(int fd, int *closes) noexcept : m_fd(fd), m_closes(closes) {} 14 │ ~MoveHandle() { reset(); }───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Verifying Heap Teardown Order and Allocator System Calls
- Check
./verifyoutput:RAII closes=1 teardown=early->btn->label->root stack_faults=1.
GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Verifying Heap Teardown Order and Allocator System Calls
- Notice in
stracehowbrk()establishes the C++ process heap arena once at startup, followed by all `new…
GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Verifying Heap Teardown Order and Allocator System Calls
learner@ksa:~/gl-q01/m01-l02$ g++ -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 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Verifying Heap Teardown Order and Allocator System Calls
learner@ksa:~/gl-q01/m01-l02$ strace -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 · 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
QObjectand has a parent,…
GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Ownership Collisions in Production Qt 6 Codebases
- Notice how
Q_DISABLE_COPY_MOVEturns accidental value-copy bugs (void showPanel(QWidget w)) into immedi…
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 · 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 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Guided Practice
- Modify
verify.cppto test the reverse stack declaration order: `{ ObjectNode parent("p", nullptr, false,…
GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Independent Practice
- Write a C++20 Rule-of-Five
MmapRegionclass wrapping avoid *pointer andstd::size_tbyte length wit…
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.
Correct: A
Automatic storage unwinds strictly in reverse declaration order: win was declared after lbl, so ~win() runs while lbl is still attached and passes stack address &lbl to operator delete.
Common misconception: Assuming QObject::setParent() alters C++ stack local destruction order or detects stack pointers.
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.
Correct: D
Passing this registers m_status inside QObjectPrivate::children; adding std::unique_ptr assigns freeing responsibility for one heap block to two separate destructors.
Common misconception: Applying std::unique_ptr mechanically to pointers already owned by an intrusive QObject parent.
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.
Correct: C
On self-move (x = std::move(x)), calling reset() unconditionally closes the live descriptor held by both this and other.
Common misconception: Assuming self-move can never occur through aliases, swaps, or algorithm rearrangements.
GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Summary
- Destroying a parent
QObjectwalksQObjectPrivate::childrenand callsdeleteon remaining children, so parenting a stack-allocated child onto a shorter-lived stack parent causes a fatal invalid-free crash. QObjectdeletes its copy constructor and copy-assignment operator (Q_DISABLE_COPY_MOVE) because tree identity,thisparent links, and live signal connections cannot be meaningfully cloned.- Deleting a heap-allocated child
QObjectbefore its parent executes~QObject(), which removesthisfrom the parent'schildrenlist 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::exchangemove transfer) while storingthis-parented child widgets as raw non-owning pointers.
GL-Q01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Key takeaways
QObjectdeletes its copy constructor and copy-assignment operator (Q_DISABLE_COPY_MOVE) because tree identity,thisparent links, and live signal connections cannot be meaningfully cloned.- Deleting a heap-allocated child
QObjectbefore its parent executes~QObject(), which removesthisfrom the parent'schildrenlist 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::exchangemove transfer) while storingthis-parented child widgets as raw non-owning pointers.
GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Virtual Dispatch, Inheritance, Operator Overloads & C++20 Concepts
What you'll learn
- Measure exact object size (
sizeof) growth fromvptrinsertion and verify base-pointer polymorphic teardown viavirtualdestructors. - Implement
constexprC++20 value-type operator overloads (operator<=>,operator==,operator+) cleanly separated from identity-basedQObjectclasses. - Partition high-rate C++20
concept-constrained sample filters from non-templatedQObjectpresenters and benchmark dispatch latency withCLOCK_MONOTONIC.
GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Dynamic Widget Polymorphism Meets Zero-Overhead C++20 Static Constraints
- Every
QObjectinstance begins in memory with a hidden virtual table pointer (vptr: 8 bytes on LP64 `x86…
GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Dynamic Widget Polymorphism Meets Zero-Overhead C++20 Static Constraints
- Simultaneously,
mocenforces a hard architectural rule: aQ_OBJECTclass cannot be a class template (`t…
GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Dynamic Widget Polymorphism Meets Zero-Overhead C++20 Static Constraints
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 · 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 · 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 · 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 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Inside Itanium C++ ABI Object Layout and Concept Instantiation
- Inspect
telemetry_sink.hppbelow.
GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Inside Itanium C++ ABI Object Layout and Concept Instantiation
- Next, look at how
TelemetryPresenterworks aroundmoc's no-class-template rule:TelemetryPresenterit…
GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Inside Itanium C++ ABI Object Layout and Concept Instantiation
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 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# telemetry_sink.hpp
learner@ksa:~/gl-q01/m01-l03$ bat telemetry_sink.hpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: telemetry_sink.hpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #pragma once 2 │ #include <QObject> 3 │ #include <compare> 4 │ #include <concepts> 5 │ #include <cstdint> 6 │ #include <span> 7 │ 8 │ namespace hmi { 9 │ 10 │ struct MilliVolts { 11 │ std::int32_t mv = 0; 12 │ 13 │ constexpr auto operator<=>(const MilliVolts &) const noexcept = default; 14 │ constexpr MilliVolts operator+(MilliVolts rhs) const noexcept {───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# cpp20-polymorphism
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 · 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 · 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 (
50500mV) and destructor counts (1/1)…
GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m01-l03$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <algorithm> 2 │ #include <array> 3 │ #include <cassert> 4 │ #include <compare> 5 │ #include <concepts> 6 │ #include <cstdint> 7 │ #include <cstdio> 8 │ #include <ctime> 9 │ #include <memory> 10 │ 11 │ namespace hmi { 12 │ 13 │ struct MilliVolts { 14 │ std::int32_t mv = 0;───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Confirming vptr Size Growth and Polymorphic Teardown
- Verify
./verifyoutput:sizeof_mv=4 vptr=+8b dtors=1/1on 64-bit Linux, followed by medianvirt_p50a…
GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Confirming vptr Size Growth and Polymorphic Teardown
- Notice in
stracethatclock_gettime(CLOCK_MONOTONIC)resolves via theLinux kernelvDSOshared page…
GL-Q01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Confirming vptr Size Growth and Polymorphic Teardown
learner@ksa:~/gl-q01/m01-l03$ g++ -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 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Confirming vptr Size Growth and Polymorphic Teardown
learner@ksa:~/gl-q01/m01-l03$ strace -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 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Polymorphic Slicing, Overload Hiding, and moc Template Limits
- Module 1 has established your C++20 and
QObjectarchitectural foundation: isolated target CMake autogen g…
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_raiiengineering studio below, where…
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 · 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 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Guided Practice
- Add a second
SampleFilter-conforming structClampedFiltertoverify.cppthat clamps each incoming `Mi…
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 · 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.
Correct: D
QMetaObject tables are concrete translation-unit symbols emitted by moc before g++ instantiates templates; keep Q_OBJECT on non-template classes and use member function templates.
Common misconception: Assuming moc runs inside the C++ compiler's template instantiation engine.
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.
Correct: C
Having a pure virtual method (send) does NOT make the destructor virtual; deleting a derived instance via ICanBus * without virtual ~ICanBus() is undefined behavior.
Common misconception: Believing any virtual member function automatically makes the class destructor virtual.
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.
Correct: B
override verifies that a matching virtual signature exists in a base class, and final proves no further subclass can override methods when accessed via AlarmBanner * or AlarmBanner &.
Common misconception: Thinking final removes the inherited base vptr rather than enabling leaf call devirtualization.
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 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Summary
- Declaring any
virtualfunction adds one hiddenvptrper instance pointing to a per-classvtable, whereas a C++20conceptconstrains 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
overridecatches base-signature drift at compile time, while marking leaf widgetsfinallets the optimizer devirtualize calls through leaf pointers. - Value structs such as fixed-point
MilliVoltscleanly overloadoperator<=>andoperator+, whereasQ_OBJECTclasses forbid copy/value operators and cannot be C++ class templates becausemocemits concreteQMetaObjectglobals.
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
overridecatches base-signature drift at compile time, while marking leaf widgetsfinallets the optimizer devirtualize calls through leaf pointers. - Value structs such as fixed-point
MilliVoltscleanly overloadoperator<=>andoperator+, whereasQ_OBJECTclasses forbid copy/value operators and cannot be C++ class templates becausemocemits concreteQMetaObjectglobals.
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.
- 2.1 Qt 6 Module Split, d_ptr PIMPL ABI & Implicitly Shared COW Buffers
- 2.2 Qt Designer .ui XML, uic setupUi() Generation & Code-First HMIs
- 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 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Qt 6 Module Split, d_ptr PIMPL ABI & Implicitly Shared COW Buffers
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_ptrandq_ptr(Private/Public) facade whosesizeofremains invariant when private fields grow. - Eliminate accidental Copy-on-Write heap allocations on
QStringandQByteArrayread paths usingstd::as_const(),constData(), andQStringView.
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::Widgetsdrags `libQt6Wid…
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 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Binary Compatibility and Zero-Copy Value Passing in Qt 6
Figure 2.1a: d_ptr freezes sizeof(PublicClass) across Qt 6 minor releases while atomic QArrayData refcounts defer buffer cloning until mutation.
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 · 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 · 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 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Inside Qt 6 QArrayDataPointer Layout and UTF-16LE vs Byte Storage
- Qt 6 modernized
QString,QByteArray, andQList<T>around a three-wordQArrayDataPointerheader (`24…
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 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Inside Qt 6 QArrayDataPointer Layout and UTF-16LE vs Byte Storage
Figure 2.1b: Qt 6's 3-word QArrayDataPointer decouples control-block ownership (d) from payload start (ptr), powering zero-alloc QStringLiteral.
GL-Q01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# cow_pimpl_codec.cpp
learner@ksa:~/gl-q01/m02-l01$ bat cow_pimpl_codec.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: cow_pimpl_codec.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QByteArray> 2 │ #include <QString> 3 │ #include <QtGlobal> 4 │ #include <cstdint> 5 │ #include <memory> 6 │ #include <utility> 7 │ 8 │ namespace hmi { 9 │ 10 │ class FrameCodecPrivate; 11 │ 12 │ class FrameCodec { 13 │ public: 14 │ explicit FrameCodec(std::uint32_t seed);───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# QArrayData-PIMPL
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 · 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 bidirectionald_ptr/q_ptrPimplPanelfacade and a generic `CowAr…
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: iteratingByteBuf bad_loop = master;via `for (char c : bad…
GL-Q01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m02-l01$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <atomic> 2 │ #include <cassert> 3 │ #include <cstddef> 4 │ #include <cstdint> 5 │ #include <cstdio> 6 │ #include <cstring> 7 │ #include <memory> 8 │ #include <utility> 9 │ 10 │ static int g_heap_allocs = 0; 11 │ 12 │ template <typename T> 13 │ class CowArray { 14 │ struct Block {───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Verifying PIMPL Footprint and COW Allocation Counts
- Inspect
./verifyoutput: `PIMPL sizeof=8b q_eval=170 allocs_after_const=1 allocs_after_nonconst=2 utf16_b…
GL-Q01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Verifying PIMPL Footprint and COW Allocation Counts
- Meanwhile,
std::as_const(good_loop)keptg_heap_allocsat1, whereas omittingstd::as_conston `bad…
GL-Q01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Verifying PIMPL Footprint and COW Allocation Counts
learner@ksa:~/gl-q01/m02-l01$ g++ -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 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Verifying PIMPL Footprint and COW Allocation Counts
learner@ksa:~/gl-q01/m02-l01$ strace -e trace=write,exit_group ./verifywrite(1, "PIMPL sizeof=8b q_eval=170 alloc"..., 86) = 86exit_group(0) = ?+++ exited with 0 +++GL-Q01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Dangling Views, Incomplete-Type unique_ptr Destructors & False Detaches
- Mastering
d_ptr/q_ptrand implicit sharing explains why Qt 6 APIs passQStringandQByteArrayclean…
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
.uiXML forms compile viauicinto C++setupUi()headers an…
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 · 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 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Guided Practice
- Add move-assignment and an
edit_in_place(std::size_t idx, T val)method toCowArray<T>inverify.cpp,…
GL-Q01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Independent Practice
- Refactor a header-heavy sensor parser class into
sensor_parser.hppandsensor_parser.cppusing `std::un…
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.
Correct: A
C++ range-for calls copy.begin() (non-const) whenever copy is non-const; wrapping std::as_const(copy) selects cbegin() and avoids the false detach.
Common misconception: Assuming QString::begin() can inspect the loop body to see that *it is never written.
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.
Correct: D
Compiled callers bake sizeof(PublicClass) into stack frames and subclasses; isolating fields in heap-allocated *Private keeps the public layout fixed while q_ptr links back to the owner.
Common misconception: Believing C++ private: access control hides member variables from sizeof and binary layout.
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.
Correct: C
Linking Qt6::Widgets transitively adds Qt6::Gui and display/font DT_NEEDED libraries that are unnecessary on a headless daemon.
Common misconception: Linking Qt6::Widgets out of habit on non-GUI services and bloating rootfs dependencies.
GL-Q01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Summary
- Qt 6 splits
QtCore(non-GUI event/meta/IPC),QtGui(windows, fonts,QPainter, RHI), andQtWidgetsso headless daemons linkQt6::Corewithout pulling Wayland or X11 display dependencies. - Public Qt classes keep
sizeof(PublicClass)constant across minor library upgrades by storing internal fields in a*Privateheap struct accessed viad_ptr(Q_DECLARE_PRIVATE) with back-pointerq_ptr(Q_DECLARE_PUBLIC). QString(UTF-16LEchar16_tunits) andQByteArray(raw bytes) share one atomically reference-countedQArrayDatablock across copies until a mutating call triggersdetach()whenref > 1.- Iterating a shared non-const
QStringorQByteArraywithfor (auto ch : buf)invokes non-constbegin()and forces an unnecessary deep heap copy unless wrapped instd::as_const(buf)or read viaconstData().
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*Privateheap struct accessed viad_ptr(Q_DECLARE_PRIVATE) with back-pointerq_ptr(Q_DECLARE_PUBLIC). QString(UTF-16LEchar16_tunits) andQByteArray(raw bytes) share one atomically reference-countedQArrayDatablock across copies until a mutating call triggersdetach()whenref > 1.- Iterating a shared non-const
QStringorQByteArraywithfor (auto ch : buf)invokes non-constbegin()and forces an unnecessary deep heap copy unless wrapped instd::as_const(buf)or read viaconstData().
GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Qt Designer .ui XML, uic setupUi() Generation & Code-First HMIs
What you'll learn
- Dissect every statement emitted by
uicinsideUi_Panel::setupUi(QWidget *)andretranslateUi(QWidget *). - Eliminate silent field regressions from
on_<objectName>_<signal>slots by enforcing explicit pointer-to-memberQObject::connectwiring. - Architect clean private
Ui::Panelwrappers and parameterized code-first channel strips with stableobjectNametest hooks.
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.qmlscenes often assume a Qt Designerpanel.uiXML…
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,uicemitsQMetaObject::connectSlotsByName(root).
GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# What Actually Happens to a Designer .ui File During Compilation
Figure 2.2a: uic emits ordinary C++ widget allocations in ui_*.h, making explicit PMF connect compile-time safe on widget renames.
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 · 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 · 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 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Anatomy of Generated ui_*.h Code and Hybrid Form Composition
- Notice a subtle ownership detail when
PumpPanelholdsstd::unique_ptr<Ui::PumpPanel> m_uiin `panel_uic…
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 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Anatomy of Generated ui_*.h Code and Hybrid Form Composition
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 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# panel_uic_vs_code.cpp
learner@ksa:~/gl-q01/m02-l02$ bat panel_uic_vs_code.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: panel_uic_vs_code.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QCoreApplication> 2 │ #include <QEvent> 3 │ #include <QHBoxLayout> 4 │ #include <QLabel> 5 │ #include <QPushButton> 6 │ #include <QWidget> 7 │ #include <array> 8 │ #include <memory> 9 │ 10 │ // Exact structure emitted by uic into ui_pump_panel.h: 11 │ class Ui_PumpPanel { 12 │ public: 13 │ QHBoxLayout *rootRow = nullptr; 14 │ QPushButton *haltDriveBtn = nullptr;───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# uic
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 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Simulating uic setupUi(), Retranslation & Rename Hazards in C++20
- In
verify.cpp, we modelUi_PumpPanel::setup_ui()andretranslate_ui()in pure ISO C++20, populating a…
GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Simulating uic setupUi(), Retranslation & Rename Hazards in C++20
- Watch what happens when
eStopBtnis renamed tohaltDriveBtnin the form descriptor: `connect_slots_by_n…
GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m02-l02$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <array> 2 │ #include <cassert> 3 │ #include <cstdio> 4 │ #include <memory> 5 │ #include <string> 6 │ #include <string_view> 7 │ #include <vector> 8 │ 9 │ struct SimWidget { 10 │ std::string class_name; 11 │ std::string object_name; 12 │ std::string text; 13 │ std::vector<std::unique_ptr<SimWidget>> children;───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Confirming Zero-Realloc Retranslation and Auto-Connect Breakage
- Confirm
./verifyoutputsuic children=5 de_text='Antrieb Stopp' auto_connect_after_rename=0.
GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Confirming Zero-Realloc Retranslation and Auto-Connect Breakage
- Equally clear,
auto_connect_after_rename=0proves whyon_<objectName>_<signal>is banned in industrial…
GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Confirming Zero-Realloc Retranslation and Auto-Connect Breakage
learner@ksa:~/gl-q01/m02-l02$ g++ -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 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Confirming Zero-Realloc Retranslation and Auto-Connect Breakage
learner@ksa:~/gl-q01/m02-l02$ strace -e trace=write,exit_group ./verifywrite(1, "uic children=5 de_text='Antrieb "..., 67) = 67exit_group(0) = ?+++ exited with 0 +++GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Designer Form Inheritance, Missing LanguageChange & Layout Pitfalls
- You now see
.uifiles for what they truly are: an optional ahead-of-time C++ widget-tree macro lowered by…
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
moccompilesQ_OBJECTinto packed string tables, rel…
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 · 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 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Guided Practice
- Extend
UiPumpPanelinverify.cppto store per-channel engineering unit strings updated inside `retransl…
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 · 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.
Correct: D
uic is a build-time C++ code generator; g++ compiles Ui_StatusPanel::setupUi() directly into machine instructions inside the executable.
Common misconception: Confusing ahead-of-time uic C++ generation with runtime QML loading or QUiLoader.
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.
Correct: C
m_ui->ackBtn is a C++ struct member checked by g++, whereas connectSlotsByName matches objectName strings dynamically when setupUi() executes.
Common misconception: Thinking moc or uic cross-checks on_<objectName>_<signal> names at compile time.
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.
Correct: B
Ui_PumpPanel has trivial destructor and holds raw pointers; new QPushButton(PumpPanel) registered the button in PumpPanel's QObject child list.
Common misconception: Confusing ownership of the Ui::PumpPanel helper struct with ownership of the QWidget children.
GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Summary
- During a
CMAKE_AUTOUICbuild,uiccompilespanel.uiXML ahead-of-time intoui_panel.hcontainingUi_Panel::setupUi()andretranslateUi(), shipping zero XML files or XML parsers to the target. - Composing
std::unique_ptr<Ui::Panel> m_uias aprivatemember encapsulates generated child widget pointers, whereaspublic Ui::Panelinheritance leaks internal controls to external callers. QMetaObject::connectSlotsByNamematcheson_<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::connectcalls.
GL-Q01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Key takeaways
- Composing
std::unique_ptr<Ui::Panel> m_uias aprivatemember encapsulates generated child widget pointers, whereaspublic Ui::Panelinheritance leaks internal controls to external callers. QMetaObject::connectSlotsByNamematcheson_<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::connectcalls.
GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Inside moc: Q_OBJECT, QMetaObject String Tables & qt_static_metacall
What you'll learn
- Expand
Q_OBJECT,signals:,slots:, andemitto the exact C++20 declarations compiled byg++. - Trace
void *_a[]layout (_a[0]return pointer +_a[1..N]stack argument pointers) from signal call site throughQMetaObject::activateintoqt_static_metacall. - Calculate global-to-local method index subtraction across multi-level
QObjectinheritance hierarchies.
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:, andemitlike magical language extensions hidden inside…
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::readingUpdatedcome from if you only wrote its prototype in `press…
GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Zero Compiler Magic: How Signals Become Ordinary C++ Function Calls
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 · 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 · 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 · 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 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Dissecting moc_*.cpp Byte-for-Byte: String Tables, _a[] & Inheritance
- Why did Qt introduce
qt_static_metacallinstead of making every singleslota C++virtualfunction?
GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Dissecting moc_*.cpp Byte-for-Byte: String Tables, _a[] & Inheritance
- Examine
pressure_meta.hppbelow, which pairs a Qt 6.8PressureSensorclass with the exact annotated C++…
GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Dissecting moc_*.cpp Byte-for-Byte: String Tables, _a[] & Inheritance
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 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# pressure_meta.hpp
learner@ksa:~/gl-q01/m02-l03$ bat pressure_meta.hpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: pressure_meta.hpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #pragma once 2 │ #include <QObject> 3 │ #include <cstdint> 4 │ 5 │ namespace hmi { 6 │ 7 │ class PressureSensor : public QObject { 8 │ Q_OBJECT 9 │ public: 10 │ explicit PressureSensor(QObject *parent = nullptr) : QObject(parent) {} 11 │ 12 │ void ingestSample(std::int32_t kPa, std::uint32_t faultMask) { 13 │ if (kPa != m_lastKpa || faultMask != m_lastMask) { 14 │ m_lastKpa = kPa;───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# moc
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 · 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 ofmoc's generated tables: aconstexpr`MetaString…
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 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m02-l03$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <array> 2 │ #include <cassert> 3 │ #include <cstdint> 4 │ #include <cstdio> 5 │ #include <memory> 6 │ #include <string_view> 7 │ #include <vector> 8 │ 9 │ namespace hmi { 10 │ 11 │ struct OffsetLen { 12 │ std::uint32_t offset; 13 │ std::uint32_t len; 14 │ };───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Verifying String Table Slicing and void** Metacall Return Values
- Confirm
./verifyprintsmoc sig='readingUpdated' rx_kpa=245 mask=0x4 ret=3100 base_reset=1.
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
gdband seeQMetaObject::activate-> `qt_static_metacal…
GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Verifying String Table Slicing and void** Metacall Return Values
learner@ksa:~/gl-q01/m02-l03$ g++ -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 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Verifying String Table Slicing and void** Metacall Return Values
learner@ksa:~/gl-q01/m02-l03$ strace -e trace=write,exit_group ./verifywrite(1, "moc sig='readingUpdated' rx_kpa="..., 67) = 67exit_group(0) = ?+++ exited with 0 +++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_ptrABI insulation, atomic C…
GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Custom QMetaType Registration & Hand-Written Signal Pitfalls
- Proceed to the
lab_m02_moc_signal_dispatchstudio below to repair a multi-slotMetaEndpointrouter supp…
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 · 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 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Guided Practice
- Add a third inheritance level
CalibratedSensor : public DerivedSensortoverify.cppwith `method_offset…
GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Independent Practice
- Open
labs/lab_m02_moc_signal_dispatch/and repair all three defects instarter/core.cpp—off-by-one `_a[…
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.
Correct: C
moc reserves _a[0] for return storage (nullptr on void emissions) and places arguments 1..N at _a[1].._a[N].
Common misconception: Indexing _a[0] as the first parameter instead of _a[1].
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.
Correct: B
#define emit is an empty readability macro and #define signals public makes signal member function pointers accessible to external QObject::connect callers.
Common misconception: Assuming emit is a C++ operator or Qt 4 protected: visibility still applies to Qt 6 signals:.
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.
Correct: A
Delegating upward peels off ancestor method counts dynamically, keeping Derived's switch (_id) zero-based (0..method_count-1).
Common misconception: Thinking moc hardcodes global method indices across base classes at header-generation time.
GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Lab: lab_m02_moc_signal_dispatch
- Debugging subtle Qt 6 signal bugs—nested
QSignalBlockerscopes prematurely unblocking an editor, custom `…
Verify: ./check.sh exits 0.
GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Summary
- In
<qtmetamacros.h>,emitexpands to nothing,slotsexpands to nothing, andsignalsexpands topublicso callers can pass&Sender::signalNameinto PMFQObject::connect. - Emitting a
Q_OBJECTsignal invokes amoc-generated C++ member function that packs operand addresses intovoid *_a[](_a[0]return storage,_a[1..N]argument addresses) and callsQMetaObject::activate. mocpacks class, signal, slot, and parameter names into one contiguous.rodataqt_meta_stringdataoffset/length table alongsideqt_meta_datainteger method descriptors, requiring zero startup heap allocations.qt_metacalldelegates toSuperClass::qt_metacallfirst, subtracting each base class's method count from_idsoqt_static_metacallswitches on a zero-based local method index.
GL-Q01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Key takeaways
- Emitting a
Q_OBJECTsignal invokes amoc-generated C++ member function that packs operand addresses intovoid *_a[](_a[0]return storage,_a[1..N]argument addresses) and callsQMetaObject::activate. mocpacks class, signal, slot, and parameter names into one contiguous.rodataqt_meta_stringdataoffset/length table alongsideqt_meta_datainteger method descriptors, requiring zero startup heap allocations.qt_metacalldelegates toSuperClass::qt_metacallfirst, subtracting each base class's method count from_idsoqt_static_metacallswitches on a zero-based local method index.
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.
- 3.1 Pointer-to-Member QObject::connect, Context Lifetimes & Lambda Hazards
- 3.2 Event Loops, postEvent vs sendEvent & QObject::eventFilter
- 3.3 Monotonic QTimer, Precise vs Coarse Coalescing & GUI Frame Stalls
lab → Cooperative Reactor Loop: Priority Events, LIFO Filters & Monotonic Timers
GL-Q01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Pointer-to-Member QObject::connect, Context Lifetimes & Lambda Hazards
What you'll learn
- Eliminate use-after-free and wrong-thread races in
[this]-capturing lambdas by supplying the 4-argument receiver contextQObject *. - Wire overloaded and prefix-argument member slots cleanly using
qOverload<...>()and PMFQObject::connect. - Prevent duplicate slot invocations across repeated state transitions using
Qt::UniqueConnectionandQMetaObject::Connectionhandles.
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 · 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 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# The Number-One Use-After-Free Crash in Modern C++20 Qt 6 Codebases
Figure 3.1a: Every lambda capturing widget state MUST pass a context QObject* as the 3rd argument to QObject::connect.
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 · 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 · 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 · 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
mocknowing the lambda's signature?
GL-Q01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Inside QSlotObjectBase, Prefix Arity Dropping & UniqueConnection
- Now understand why
Qt::UniqueConnectionworks on&DiagnosticPopup::refreshBadgein `pmf_lifetime_panel.…
GL-Q01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Inside QSlotObjectBase, Prefix Arity Dropping & UniqueConnection
Figure 3.1b: Dual-linked Connection nodes let either ~Sender() or ~Context() sever a slot in O(1) list manipulation.
GL-Q01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# pmf_lifetime_panel.cpp
learner@ksa:~/gl-q01/m03-l01$ bat pmf_lifetime_panel.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: pmf_lifetime_panel.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QLabel> 2 │ #include <QMetaObject> 3 │ #include <QObject> 4 │ #include <QString> 5 │ #include <QWidget> 6 │ 7 │ namespace hmi { 8 │ 9 │ class TelemetryBus : public QObject { 10 │ Q_OBJECT 11 │ public: 12 │ explicit TelemetryBus(QObject *parent = nullptr) : QObject(parent) {} 13 │ signals: 14 │ void faultRaised(int code, const QString &subsystem);───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# QObject-connect
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 · 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++20Signal<Args...>dispatcher trackingContextObject`std::weak_ptr<…
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(): callingconnect_pmftwice withunique = trueregisters only one slot…
GL-Q01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m03-l01$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <algorithm> 2 │ #include <cassert> 3 │ #include <cstdio> 4 │ #include <functional> 5 │ #include <memory> 6 │ #include <vector> 7 │ 8 │ namespace hmi { 9 │ 10 │ class ContextObject { 11 │ public: 12 │ ContextObject() : m_alive(std::make_shared<bool>(true)) {} 13 │ virtual ~ContextObject() { *m_alive = false; } 14 │ ContextObject(const ContextObject &) = delete;───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Confirming UniqueConnection Deduplication and Context Pruning
- Verify
./verifyprintsPMF unique_dup=0 ctx_sum=35 one_shot=1 pruned=0 uaf_3arg=1.
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 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Confirming UniqueConnection Deduplication and Context Pruning
learner@ksa:~/gl-q01/m03-l01$ g++ -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 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Confirming UniqueConnection Deduplication and Context Pruning
learner@ksa:~/gl-q01/m03-l01$ strace -e trace=write,exit_group ./verifywrite(1, "PMF unique_dup=0 ctx_sum=35 one_"..., 59) = 59exit_group(0) = ?+++ exited with 0 +++GL-Q01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Qt::UniqueConnection on Lambdas & Multi-Pointer Capture Traps
- With 4-argument context-bound
QObject::connectandQt::UniqueConnectionin your toolkit, signal connect…
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 · 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 · 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 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Guided Practice
- Extend
Signalinverify.cppto support prefix-argument binding (`Signal<int, int>::connect_0arg(ctx, fn…
GL-Q01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Independent Practice
- Audit a multi-dialog HMI workflow where a temporary
CalibrationWizardconnects to a singleton `SensorMana…
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.
Correct: D
Without a 3rd-argument context QObject *, Qt has no receiver thread affinity to queue onto and invokes the lambda synchronously on the emitting worker thread!
Common misconception: Believing C++ templates can introspect variables captured inside a lambda closure.
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.
Correct: C
Qt's FunctionPointer template traits unpack only the leading arguments accepted by the slot and ignore unneeded trailing signal arguments.
Common misconception: Thinking PMF connect requires identical argument counts between signal and slot.
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.
Correct: B
Qt::UniqueConnection checks existing connections on bus for the same signal, receiver, and PMF slot, preventing N-times duplicate slot execution.
Common misconception: Thinking UniqueConnection means exclusive single-subscriber multicast rather than duplicate-pair prevention.
GL-Q01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Summary
- Three-argument
QObject::connect(sender, &S::sig, lambda)binds connection lifetime solely tosender, causing a fatal use-after-free crash iflambdacaptures[this]on a shorter-lived receiverQWidget. - Four-argument
QObject::connect(sender, &S::sig, receiver, lambda)ties the connection to both endpoints so~QObject()onreceiverdisconnects the closure automatically andQt::AutoConnectionqueues ontoreceiver's thread. - Pointer-to-member
QObject::connectverifies parameter conversions at compile time viaQtPrivate::FunctionPointertraits and permits slots to accept a shorter prefix of the signal's arguments. - Passing
Qt::UniqueConnectionbitwise-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 · 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()onreceiverdisconnects the closure automatically andQt::AutoConnectionqueues ontoreceiver's thread. - Pointer-to-member
QObject::connectverifies parameter conversions at compile time viaQtPrivate::FunctionPointertraits and permits slots to accept a shorter prefix of the signal's arguments. - Passing
Qt::UniqueConnectionbitwise-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 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Event Loops, postEvent vs sendEvent & QObject::eventFilter
What you'll learn
- Enforce strict stack allocation for synchronous
sendEventcalls andnewheap transfer for asynchronouspostEventcalls. - Implement a central LIFO
QObject::eventFiltersafety interlock that consumes prohibited operator input (return true) while forwarding benign events (return false). - Contrast
QWidget::update()posted repaint coalescing against synchronousQWidget::repaint()CPU thrashing.
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Inside QCoreApplication::exec(): Multiplexing, Ownership & Interception
- When
main()entersapp.exec(), Qt's thread-localQEventDispatcherUNIX(orGlib) sleeps inside `ppol…
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Inside QCoreApplication::exec(): Multiplexing, Ownership & Interception
- Before
notify()ever callsreceiver->event(ev), it walks every watcher attached via `receiver->installE…
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Inside QCoreApplication::exec(): Multiplexing, Ownership & Interception
Figure 3.2a: postEvent takes heap ownership and compresses repaints; sendEvent borrows stack events synchronously; LIFO filters consume on true.
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 · 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 · 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 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Priority Queue Ordering, Repaint Compression & LIFO Filter Mechanics
- Look inside
safety_event_filter.cppbelow.
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Priority Queue Ordering, Repaint Compression & LIFO Filter Mechanics
- Examine
schedulePanelRefreshandinjectSyncSelfTestbelow the class as well.
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Priority Queue Ordering, Repaint Compression & LIFO Filter Mechanics
Figure 3.2b: Scheduling UpdateRequest at LowEventPriority (-1) guarantees all pending data mutations settle before a single paintEvent runs.
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# safety_event_filter.cpp
learner@ksa:~/gl-q01/m03-l02$ bat safety_event_filter.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: safety_event_filter.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QCoreApplication> 2 │ #include <QEvent> 3 │ #include <QKeyEvent> 4 │ #include <QObject> 5 │ #include <QWidget> 6 │ 7 │ namespace hmi { 8 │ 9 │ class JogInterlockFilter final : public QObject { 10 │ Q_OBJECT 11 │ public: 12 │ explicit JogInterlockFilter(QObject *parent = nullptr) : QObject(parent) {} 13 │ 14 │ void setGuardClosed(bool closed) noexcept { m_guardClosed = closed; }───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# QCoreApplication-events
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 · 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++20EventDispatchermodeling priority-sorted `post_event(std:…
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Verifying Priority Draining, Paint Compression & LIFO Filters in C++20
- Inspect
main():auditis installed first anddooris installed second (LIFO).
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m03-l02$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <algorithm> 2 │ #include <cassert> 3 │ #include <cstdio> 4 │ #include <memory> 5 │ #include <vector> 6 │ 7 │ namespace hmi { 8 │ 9 │ enum class EvType { KeyPress, UpdateRequest }; 10 │ 11 │ struct Ev { 12 │ EvType type; 13 │ int key = 0; 14 │ };───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Confirming LIFO Interception and Repaint Coalescing
- Verify
./verifyprintsEvents blocked=1 audit=1 keys=2 paints=1 drained=2.
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Confirming LIFO Interception and Repaint Coalescing
- Notice how encoding
post_event's parameter asstd::unique_ptr<Ev>in C++20 makes passing a stack addres…
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Confirming LIFO Interception and Repaint Coalescing
learner@ksa:~/gl-q01/m03-l02$ g++ -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 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Confirming LIFO Interception and Repaint Coalescing
learner@ksa:~/gl-q01/m03-l02$ strace -e trace=write,exit_group ./verifywrite(1, "Events blocked=1 audit=3 keys=2 "..., 51) = 51exit_group(0) = ?+++ exited with 0 +++GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Blank Widgets From Bad Filters & Nested processEvents() Re-Entrancy
- You now control every stage of
QEventdelivery: stacksendEventversus heappostEvent, `LowEventPrior…
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_MONOTONICtimer…
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 · 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 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Guided Practice
- Modify
install_event_filterinverify.cppto verify what happens when the SAME filter&auditis insta…
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Independent Practice
- Design an inactivity screen-dimmer
IdleTouchFilterinstalled once onQApplication::instance()(global a…
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.
Correct: C
postEvent takes ownership of the raw QEvent * pointer and unconditionally deletes it when draining the posted queue.
Common misconception: Confusing asynchronous heap-owning postEvent with synchronous stack-borrowing sendEvent.
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.
Correct: B
Qt evaluates installed event filters in LIFO order (most recently installed first) and aborts delivery immediately when any filter returns true.
Common misconception: Assuming FIFO filter execution or assuming remaining filters still observe a consumed event.
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.
Correct: A
update() schedules and coalesces QEvent::UpdateRequest at Qt::LowEventPriority, whereas repaint() forces immediate synchronous rasterization on every call.
Common misconception: Calling repaint() in data-arrival slots and burning 100% CPU on redundant intermediate draws.
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Summary
QCoreApplication::sendEvent(dst, &ev)dispatches a stack-allocatedQEventsynchronously on the current call stack without deletingev, whereaspostEvent(dst, new Ev)queues a heap event asynchronously anddeletes it after delivery.- Passing the address of a stack-allocated
QEventintoQCoreApplication::postEventcauses fatal heap corruption when the event dispatcher drains the queue and executesdelete event. - Pre-target watchers installed via
target->installEventFilter(filterObj)execute in LIFO order (last installed runs first); returningtrueconsumes the event immediately while returningfalseforwards it towardtarget->event(). - Qt compresses queued
QEvent::UpdateRequestevents posted byQWidget::update()so bursts of state changes within one event-loop turn coalesce into a singleQPaintEventraster pass.
GL-Q01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Key takeaways
- Passing the address of a stack-allocated
QEventintoQCoreApplication::postEventcauses fatal heap corruption when the event dispatcher drains the queue and executesdelete event. - Pre-target watchers installed via
target->installEventFilter(filterObj)execute in LIFO order (last installed runs first); returningtrueconsumes the event immediately while returningfalseforwards it towardtarget->event(). - Qt compresses queued
QEvent::UpdateRequestevents posted byQWidget::update()so bursts of state changes within one event-loop turn coalesce into a singleQPaintEventraster pass.
GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Monotonic QTimer, Precise vs Coarse Coalescing & GUI Frame Stalls
What you'll learn
- Prove why
CLOCK_MONOTONICphase-locked advancement (deadline += period) eliminates cumulative drift and survives NTP wall-clock jumps. - Select
Qt::PreciseTimerversusQt::CoarseTimer(5%coalescing window) and bindQTimer::singleShotsafely to receiver lifetimes. - Instrument GUI slot execution budgets with
QElapsedTimerto catch main-thread stalls that starveQPaintEvent/WM_PAINTdelivery.
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-01RTC time beforechronydstepsCLOCK_REALTIMEfo…
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 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Wall-Clock Jumps, 5% Timer Jitter & Cooperative Frame Starvation
Figure 3.3a: GUI-thread QTimers and QPaintEvents share one cooperative thread: blocking any slot freezes both timers and screen repaints.
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 · 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 · 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 · 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 msperiod) industrial touchscreen: (1) `epoll_…
GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# How Blocking Slots Starve Both QTimerInfoList and QPaintEvent
- If step (2) performs a synchronous
90 msserial retry or unindexed SQLite scan, step (4) cannot execute f…
GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# How Blocking Slots Starve Both QTimerInfoList and QPaintEvent
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 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# monotonic_frame_watchdog.cpp
learner@ksa:~/gl-q01/m03-l03$ bat monotonic_frame_watchdog.cpp───────┬─────────────────────────────────────────────────────────────────────────────────── │ File: monotonic_frame_watchdog.cpp───────┼─────────────────────────────────────────────────────────────────────────────────── 1 │ #include <QElapsedTimer> 2 │ #include <QObject> 3 │ #include <QTimer> 4 │ #include <cstdint> 5 │ 6 │ namespace hmi { 7 │ 8 │ class FrameWatchdog final : public QObject { 9 │ Q_OBJECT 10 │ public: 11 │ static constexpr int kPeriodMs = 20; 12 │ static constexpr std::int64_t kSlotBudgetUs = 8000; // 8 ms (< 16.67 ms 60 Hz) 13 │ 14 │ explicit FrameWatchdog(QObject *parent = nullptr)───────┴───────────────────────────────────────────────────────────────────────────────────GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# QTimer-QElapsedTimer
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 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Proving Monotonic Phase-Lock, 5% Coarse Window & Paint Starvation in C++20
- In
verify.cpp, we invoke theLinux kernelSYS_clock_gettimesyscall withCLOCK_MONOTONICdirectly s…
GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m03-l03$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <cassert> 2 │ #include <cstdint> 3 │ #include <cstdio> 4 │ #include <ctime> 5 │ #include <functional> 6 │ #include <memory> 7 │ #include <sys/syscall.h> 8 │ #include <unistd.h> 9 │ #include <vector> 10 │ 11 │ namespace hmi { 12 │ 13 │ enum class TimerMode { Precise, Coarse };───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inspecting CLOCK_MONOTONIC Syscalls and Post-Stall Phase Alignment
- Inspect both
./verifystdout and thestracecapture!
GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inspecting CLOCK_MONOTONIC Syscalls and Post-Stall Phase Alignment
- In
strace, confirm the two realclock_gettime(CLOCK_MONOTONIC, ...)kernel calls preceding `write(1, ..…
GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inspecting CLOCK_MONOTONIC Syscalls and Post-Stall Phase Alignment
learner@ksa:~/gl-q01/m03-l03$ g++ -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 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inspecting CLOCK_MONOTONIC Syscalls and Post-Stall Phase Alignment
learner@ksa:~/gl-q01/m03-l03$ strace -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 · 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 +
QObjectownership…
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_timersstudio below to integrate priority posted events, LIFO filters, an…
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 · 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 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Guided Practice
- Add a simulated NTP backward wall-clock jump (
realtime_offset_ns -= 30 * 1000000000ULL) toverify.cppa…
GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Independent Practice
- Open
labs/lab_m03_event_loop_timers/and repair all three defects instarter/core.cpp—inverted FIFO fil…
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.
Correct: B
Both GUI-thread QTimer callbacks and QPaintEvent (UpdateRequest) are dispatched by QCoreApplication::exec(), which cannot run while a slot blocks the GUI call stack.
Common misconception: Thinking Qt::PreciseTimer preempts a busy thread like a hardware timer interrupt.
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.
Correct: A
QTimer defaults to Qt::CoarseTimer (5% coalescing tolerance); call setTimerType(Qt::PreciseTimer) for strict instrumentation cadences.
Common misconception: Assuming QTimer defaults to Qt::PreciseTimer out of the box.
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.
Correct: D
Without the 2nd-argument context QObject *, the timer remains active after ~Dialog() and invokes the [this] lambda on freed memory.
Common misconception: Forgetting the context QObject * parameter on QTimer::singleShot.
GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Lab: lab_m03_event_loop_timers
- Industrial HMIs fail intermittent soak tests when a safety
eventFilterruns in the wrong order, periodic…
Verify: ./check.sh exits 0.
GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Summary
QTimerandQElapsedTimerschedule deadlines onCLOCK_MONOTONIC, advancing periodic targets phase-locked (next_ns += period_ns) so NTP or operator wall-clock jumps never freeze or burst HMI timers.QTimerdefaults toQt::CoarseTimer, which rounds wakeups within a5%interval window to batch OS wakeups; deterministic control/telemetry cadences requiresetTimerType(Qt::PreciseTimer).- Context-bound
QTimer::singleShot(ms, receiver, slot)cancels pending one-shot callbacks automatically ifreceiveris destroyed before the deadline expires. - Because
QTimerandQPaintEvent(WM_PAINT/UpdateRequest) share the cooperative GUI event loop, blocking a GUI-thread slot for90 msdelays every GUIQTimerand freezes frame rendering for90 ms.
GL-Q01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Key takeaways
QTimerdefaults toQt::CoarseTimer, which rounds wakeups within a5%interval window to batch OS wakeups; deterministic control/telemetry cadences requiresetTimerType(Qt::PreciseTimer).- Context-bound
QTimer::singleShot(ms, receiver, slot)cancels pending one-shot callbacks automatically ifreceiveris destroyed before the deadline expires. - Because
QTimerandQPaintEvent(WM_PAINT/UpdateRequest) share the cooperative GUI event loop, blocking a GUI-thread slot for90 msdelays every GUIQTimerand freezes frame rendering for90 ms.
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.
- 4.1 Buttons, Checkable Groups & Safety Interlocks
- 4.2 Numeric/Text Editors, QValidator States & QSignalBlocker Anti-Echo
- 4.3 QBoxLayout, QGridLayout, QFormLayout, QSpacerItem & Stretch Solvers
lab → Lab 4: 1D/2D Box & Grid Layout Geometry Solver with Max-Cap Redistribution
GL-Q01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Buttons, Checkable Groups & Safety Interlocks
What you'll learn
- Enforce two-step
Disarmed -> Armed -> Actuated -> Trippedsafety interlocks acrossQPushButton,QToolButton, andQActionwithsetAutoRepeat(false). - Coordinate layout-independent
QRadioButtonmutual exclusion viaQButtonGroup, hierarchicalQCheckBoxtristate rollups, andQDialogButtonBoxrole ordering. - Distinguish interactive
clicked(bool)from programmatictoggled(bool)while sizing44x44 pxminimum touch targets for gloved operators.
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 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Multi-Surface Command Drift, Auto-Repeat Bounce, and Touch Ergonomics
QActioneliminates command drift by owning the authoritativeenabled,checked,text, icon, and `QKe…
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 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Multi-Surface Command Drift, Auto-Repeat Bounce, and Touch Ergonomics
Figure 4.1a: Actuator command path from touch target geometry through QButtonGroup and QAction interlocks.
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 · 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 · 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 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# QButtonGroup Exclusivity, Tristate QCheckBox, and QDialogButtonBox Roles
- Beginners often assume
QRadioButtonmutual exclusion requires wrapping buttons inside oneQGroupBox.
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 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# QButtonGroup Exclusivity, Tristate QCheckBox, and QDialogButtonBox Roles
- Finally, distinguish
clicked(bool)fromtoggled(bool)on checkable buttons, and useQDialogButtonBox…
GL-Q01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# QButtonGroup Exclusivity, Tristate QCheckBox, and QDialogButtonBox Roles
Figure 4.1b: Qt 6 button widget contracts, tristate rollup encodings, and semantic dialog roles.
GL-Q01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# interlock_button_panel.cpp
learner@ksa:~/gl-q01/m04-l01$ bat interlock_button_panel.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: interlock_button_panel.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QAction> 2 │ #include <QButtonGroup> 3 │ #include <QCheckBox> 4 │ #include <QDialogButtonBox> 5 │ #include <QHBoxLayout> 6 │ #include <QKeySequence> 7 │ #include <QPushButton> 8 │ #include <QRadioButton> 9 │ #include <QToolButton> 10 │ #include <QVBoxLayout> 11 │ #include <QWidget> 12 │ #include <array> 13 │ 14 │ class SpindleSafetyBar final : public QWidget {───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# QAbstractButton-QButtonGroup
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 · 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 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Host C++20 Verifier for Two-Step Interlocks, Button Groups, and Tristate Rollups
- Inspect
verify.cppbelow.
GL-Q01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m04-l01$ bat verify.cpp───────┬────────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼────────────────────────────────────────────────────────────────────────────────── 1 │ #include <array> 2 │ #include <cassert> 3 │ #include <cstdio> 4 │ 5 │ enum class CheckState : int { Unchecked = 0, PartiallyChecked = 1, Checked = 2 }; 6 │ enum class Interlock : int { Disarmed = 0, Armed = 1, Tripped = 2 }; 7 │ 8 │ struct TouchBox { 9 │ int width_px; 10 │ int height_px; 11 │ constexpr bool meets_hmi_minimum() const noexcept { 12 │ return width_px >= 44 && height_px >= 44; 13 │ } 14 │ };───────┴──────────────────────────────────────────────────────────────────────────────────GL-Q01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Verifying Interlock Transitions, Auto-Repeat Rejection, and Tristate Output
- Compile and execute
verify.cppunder strict-std=c++20 -Wall -Wextra -Werror -pedantic.
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 whileArmedand then acknowl…
GL-Q01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Verifying Interlock Transitions, Auto-Repeat Rejection, and Tristate Output
learner@ksa:~/gl-q01/m04-l01$ g++ -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 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Verifying Interlock Transitions, Auto-Repeat Rejection, and Tristate Output
learner@ksa:~/gl-q01/m04-l01$ strace -e trace=write,exit_group ./verifywrite(1, "buttons_audit: mode_id=2 tristat"..., 89) = 89exit_group(0) = ?+++ exited with 0 +++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 · 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 · 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 · 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 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Guided Practice
- Extend
InterlockHarnessinverify.cppsotrigger_start_actionalso requires `ExclusiveButtonGroup::ch…
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 · 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.
Correct: C
QAbstractButton::toggled(bool) notifies all state changes (both interactive and programmatic), whereas clicked(bool) fires only on user activation.
Common misconception: Confusing state-change notifications (toggled) with user-interaction signals (clicked).
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.
Correct: B
QAction centralizes command enablement, text, icon, and shortcut dispatch so no secondary UI surface stays unlocked during an interlock trip.
Common misconception: Duplicating setEnabled() booleans manually across separate button, menu, and shortcut slots.
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.
Correct: A
Because QButtonGroup inherits QObject rather than QWidget, it manages logical exclusivity across any visual hierarchy.
Common misconception: Assuming QButtonGroup is a visual frame widget like QGroupBox.
GL-Q01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Summary
- Disabling
autoRepeaton safety-criticalQPushButtonandQToolButtonactuators prevents a held finger or key bounce from synthesizing repeatedclicked()pulses while enforcing at least44x44 pxcapacitive touch targets. QButtonGroupis a non-visualQObjectcontainer that enforcesQRadioButtonor checkable button mutual exclusion and integer ID dispatch (idClicked) across arbitrary layouts without forcing buttons into one visualQGroupBox.QAbstractButton::toggled(bool)emits on both operator clicks and programmaticsetChecked()calls, whereasclicked(bool)emits only on interactive user activation (mouse,touch,Space, orclick()).- A tristate
QCheckBox(Qt::Unchecked,Qt::PartiallyChecked,Qt::Checked) summarizes mixed child enablement states, whileQDialogButtonBoxordersAcceptRole,RejectRole, andDestructiveRolebuttons per platform style.
GL-Q01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Key takeaways
QButtonGroupis a non-visualQObjectcontainer that enforcesQRadioButtonor checkable button mutual exclusion and integer ID dispatch (idClicked) across arbitrary layouts without forcing buttons into one visualQGroupBox.QAbstractButton::toggled(bool)emits on both operator clicks and programmaticsetChecked()calls, whereasclicked(bool)emits only on interactive user activation (mouse,touch,Space, orclick()).- A tristate
QCheckBox(Qt::Unchecked,Qt::PartiallyChecked,Qt::Checked) summarizes mixed child enablement states, whileQDialogButtonBoxordersAcceptRole,RejectRole, andDestructiveRolebuttons per platform style.
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Numeric/Text Editors, QValidator States & QSignalBlocker Anti-Echo
What you'll learn
- Classify live keystrokes into
QValidator::Invalid,Intermediate, andAcceptablestates so multi-digit numeric edits progress without premature commits. - Eliminate recursive
valueChangedping-pong across coupledQSpinBox,QDoubleSpinBox,QSlider,QDial,QComboBox, andQLineEditcontrols using RAIIQSignalBlocker. - Select
QPlainTextEdit(maximumBlockCount) versusQTextEdit/QTextBrowserand fixed-point integer backing to bound RAM and avoid IEEE-754 drift.
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Prefix Validation Automata and Coupled-Control Signal Ping-Pong
- Consider a manifold pressure
QLineEditconstrained to[100, 500]kPa.
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Prefix Validation Automata and Coupled-Control Signal Ping-Pong
- A companion hazard lurks inside
QSpinBoxandQDoubleSpinBox: by default,keyboardTracking()istrue…
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 coarseQSliderorQDial, an…
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Prefix Validation Automata and Coupled-Control Signal Ping-Pong
Figure 4.2a: Keystroke validation and multi-widget setpoint synchronization without recursive signal echo.
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 · 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 · 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 · 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 · 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 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# QSignalBlocker RAII, QPlainTextEdit vs QTextBrowser, and Typed Selectors
- Round out forms with typed selectors: pass
QVariantinteger IDs to `QComboBox::addItem(tr("psi"), UnitPsi…
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# QSignalBlocker RAII, QPlainTextEdit vs QTextBrowser, and Typed Selectors
Figure 4.2b: Memory and precision contracts across Qt 6 text, numeric, selector, and log widgets.
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# coupled_setpoint_console.cpp
learner@ksa:~/gl-q01/m04-l02$ bat coupled_setpoint_console.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: coupled_setpoint_console.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QComboBox> 2 │ #include <QDateTime> 3 │ #include <QDateTimeEdit> 4 │ #include <QDial> 5 │ #include <QHBoxLayout> 6 │ #include <QIntValidator> 7 │ #include <QLineEdit> 8 │ #include <QPlainTextEdit> 9 │ #include <QSignalBlocker> 10 │ #include <QSlider> 11 │ #include <QSpinBox> 12 │ #include <QTimeZone> 13 │ #include <QVBoxLayout> 14 │ #include <QWidget>───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# QValidator-QSignalBlocker
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 · 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 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Host C++20 Verifier for Range Validators, SignalBlocker Nesting, and Bounded Logs
- Examine
RangeValidator::validateinverify.cpp:'2'and'25'have fewer digits than500(3digi…
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m04-l02$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <algorithm> 2 │ #include <cassert> 3 │ #include <cctype> 4 │ #include <cstdio> 5 │ #include <deque> 6 │ #include <functional> 7 │ #include <string> 8 │ #include <string_view> 9 │ 10 │ enum class ValState { Invalid, Intermediate, Acceptable }; 11 │ 12 │ class RangeValidator { 13 │ public: 14 │ constexpr RangeValidator(int lo, int hi) noexcept : m_lo(lo), m_hi(hi) {}───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Inspecting Anti-Echo Counts, Validator Transitions, and Log Eviction
- Run
./verifyand confirmspin=243 slider=240 commits=1 nested_kept=1 log_blocks=4 oldest=seq_4.
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Inspecting Anti-Echo Counts, Validator Transitions, and Log Eviction
- Meanwhile, appending
7lines intoPlainLogRing(4)capped memory at4blocks withseq_4at the head—…
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Inspecting Anti-Echo Counts, Validator Transitions, and Log Eviction
learner@ksa:~/gl-q01/m04-l02$ g++ -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 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Inspecting Anti-Echo Counts, Validator Transitions, and Log Eviction
learner@ksa:~/gl-q01/m04-l02$ strace -e trace=write,exit_group ./verifywrite(1, "editors_audit: spin=243 slider=3"..., 85) = 85exit_group(0) = ?+++ exited with 0 +++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 · 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 · 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 · 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 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Guided Practice
- Extend
RangeValidatorinverify.cppto support signed negative temperature ranges[-40, -10]degrees…
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Independent Practice
- Build a fixed-point
CentibarSpinModelstoring pressure inint32_thundredths of a bar ([100, 500]->…
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.
Correct: B
Intermediate permits valid incomplete prefixes during editing while ensuring editingFinished() only emits once the text becomes Acceptable.
Common misconception: Assuming QValidator only has pass/fail binary states.
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.
Correct: A
If an outer caller already blocked signals on widget, ~QSignalBlocker() restores true rather than prematurely unblocking widget.
Common misconception: Assuming widget->signalsBlocked() is always false upon entering a helper method.
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.
Correct: D
QPlainTextEdit avoids rich-text DOM overhead and evicts oldest line blocks in bounded memory once maximumBlockCount is reached.
Common misconception: Using rich-text QTextEdit or QTextBrowser as an unbounded streaming log console.
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Summary
QValidatorclassifies input strings intoInvalid(rejected immediately),Intermediate(permitted while typing toward a valid value while suppressingeditingFinished()), andAcceptable(eligible to commit).- Stack-scoped
QSignalBlockersuppresses intermediate signal emissions during programmatic peer-widget updates and restores the widget's priorsignalsBlocked()boolean on scope exit. QPlainTextEditwithsetMaximumBlockCount()stores line-oriented logs in bounded plain-text blocks (O(1)eviction), whereasQTextEditandQTextBrowsermaintain a full rich-textQTextDocumentlayout tree.- Attaching typed
QVariantuser data toQComboBox::addItem(), settingQSpinBox::setKeyboardTracking(false), and pinningQDateTimeEdittoQTimeZone::UTCprevent locale drift and half-typed setpoint spikes.
GL-Q01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Key takeaways
- Stack-scoped
QSignalBlockersuppresses intermediate signal emissions during programmatic peer-widget updates and restores the widget's priorsignalsBlocked()boolean on scope exit. QPlainTextEditwithsetMaximumBlockCount()stores line-oriented logs in bounded plain-text blocks (O(1)eviction), whereasQTextEditandQTextBrowsermaintain a full rich-textQTextDocumentlayout tree.- Attaching typed
QVariantuser data toQComboBox::addItem(), settingQSpinBox::setKeyboardTracking(false), and pinningQDateTimeEdittoQTimeZone::UTCprevent locale drift and half-typed setpoint spikes.
GL-Q01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# QBoxLayout, QGridLayout, QFormLayout, QSpacerItem & Stretch Solvers
What you'll learn
- Derive exact 1D/2D widget positions and sizes from margins, visible-only spacing gaps,
sizeHint(),minimumSizeHint(), andQSizePolicy. - Distribute surplus pixels across integer stretch weights with
maxSizecap redistribution and remainder rounding so zero cumulative drift occurs. - Structure aligned multi-channel readouts and calibration dialogs using
QGridLayout,QFormLayout, andQSpacerItemwithout nested parent collisions.
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 at96 DPIand break…
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 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Why Magic Pixel Coordinates Break and How QLayoutEngine Solves Constraints
- Walk the exact 1D equation for
N_visvisible items inside widthWwith marginsm_L, m_Rand spacing `…
GL-Q01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Why Magic Pixel Coordinates Break and How QLayoutEngine Solves Constraints
Figure 4.3a: Constraint-based geometry calculation across visible items, size policies, and stretch remainders.
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 · 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 · 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 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Stretch Remainder Math, QGridLayout vs QFormLayout, and QSpacerItem
- When usable width
Uexceeds the sum of clampedsizeHint()widths,QLayoutEngineallocates surplusS…
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 · 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 aQSpacerItem(…
GL-Q01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Stretch Remainder Math, QGridLayout vs QFormLayout, and QSpacerItem
Figure 4.3b: Choosing between QBoxLayout, QGridLayout, QFormLayout, and QSpacerItem with QSizePolicy flags.
GL-Q01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# calibration_layout_grid.cpp
learner@ksa:~/gl-q01/m04-l03$ bat calibration_layout_grid.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: calibration_layout_grid.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QFormLayout> 2 │ #include <QGridLayout> 3 │ #include <QHBoxLayout> 4 │ #include <QLabel> 5 │ #include <QPushButton> 6 │ #include <QSizePolicy> 7 │ #include <QSpacerItem> 8 │ #include <QSpinBox> 9 │ #include <QVBoxLayout> 10 │ #include <QWidget> 11 │ #include <array> 12 │ 13 │ class CalibrationTelemetryPanel final : public QWidget { 14 │ Q_OBJECT───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# QLayout-QSizePolicy
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 · 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
qGeomCalcinverify.cpp: visible-only gap counting, iterative `…
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 pxwith10 pxmargins across threestretch = 1items…
GL-Q01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m04-l03$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <algorithm> 2 │ #include <cassert> 3 │ #include <cstdio> 4 │ #include <vector> 5 │ 6 │ enum class Mode { Fixed, Preferred, Expanding }; 7 │ 8 │ struct Spec { 9 │ int min_px; 10 │ int hint_px; 11 │ int max_px; 12 │ int stretch; 13 │ Mode mode; 14 │ bool visible;───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Verifying Exact Edge Alignment, Hidden-Item Gaps, and Cap Saturation
- Confirm
./verifyprintslayout_audit: rem=[101,101,100] end=312 hidden_pos2=118 capped=[130,270].
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_solverto implement and benchmark both 1D deficit/surplus solving…
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$ g++ -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 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Verifying Exact Edge Alignment, Hidden-Item Gaps, and Cap Saturation
learner@ksa:~/gl-q01/m04-l03$ strace -e trace=write,exit_group ./verifywrite(1, "layout_audit: rem=[101,101,100] "..., 73) = 73exit_group(0) = ?+++ exited with 0 +++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 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Layout Parenting Errors and Minimum-Size Clipping Pitfalls
- Keep the host-versus-target boundary clear: our
CLOCK_MONOTONICsolver benchmark measures pure C++20 inte…
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 · 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 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Guided Practice
- Extend
solve_axisinverify.cppto handle container shrinkage (surplus < 0, i.e.,avail < sum) by s…
GL-Q01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Independent Practice
- Complete
lab_m04_box_grid_layout_solverby repairing the three defects instarter/core.cpp: excluding h…
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.
Correct: A
A QWidget can own only one root QLayout; sub-layouts construct with nullptr parent and become children of root via root->addLayout(row).
Common misconception: Passing the host QWidget * pointer to every layout constructor instead of only the root layout.
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.
Correct: D
QLayoutEngine filters out invisible items prior to gap calculation so hiding a widget never leaves double-spacing holes.
Common misconception: Counting hidden widgets when multiplying (N - 1) * spacing.
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.
Correct: C
When explicit stretch factors are zero, ExpandFlag (QSizePolicy::Expanding) takes priority over plain GrowFlag (Preferred).
Common misconception: Assuming QSizePolicy::Expanding has no effect unless a nonzero stretch factor is also supplied.
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 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Summary
QLayoutEnginesubtracts margins and(N_visible - 1) * spacingfirst, locksQSizePolicy::Fixeditems tosizeHint(), clamps[minimumSize, maximumSize], and divides surplus across stretch factors without cumulative rounding drift.- Hidden widgets (
!isVisible()) consume zero pixels and zero inter-itemspacinggaps, whileQSpacerItem(addStretch) absorbs slack space without allocating aQWidgetwindow backing surface. QGridLayoutsolves shared column and row tracks (setColumnStretch,setRowStretch) across multi-row telemetry cells, whereasQFormLayoutpairs two-column label-and-field calibration rows cleanly.- Passing a
QWidget *constructor argument to a nested sub-layout (new QHBoxLayout(this)) fails because aQWidgetowns only one root layout; nested layouts construct parentless and attach viaaddLayout().
GL-Q01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Key takeaways
- Hidden widgets (
!isVisible()) consume zero pixels and zero inter-itemspacinggaps, whileQSpacerItem(addStretch) absorbs slack space without allocating aQWidgetwindow backing surface. QGridLayoutsolves shared column and row tracks (setColumnStretch,setRowStretch) across multi-row telemetry cells, whereasQFormLayoutpairs two-column label-and-field calibration rows cleanly.- Passing a
QWidget *constructor argument to a nested sub-layout (new QHBoxLayout(this)) fails because aQWidgetowns only one root layout; nested layouts construct parentless and attach viaaddLayout().
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.
- 5.1 Containers, Display Widgets & Lazy Page Budgets
- 5.2 Model/View vs Item-Widgets: QAbstractTableModel, QListView, QTreeView & Roles
- 5.3 beginInsertRows Contracts, QSortFilterProxyModel & Custom StyledItemDelegates
lab → Lab 5: Bounded FaultTableModel, Persistent Selection & Sort/Filter Proxy
GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Containers, Display Widgets & Lazy Page Budgets
What you'll learn
- Cut cold-boot latency and resident heap usage on embedded panels by lazy-instantiating
QStackedWidgetandQTabWidgetpages on first navigation. - Configure
QScrollArea::setWidgetResizable(true),QLabel::setTextFormat(Qt::PlainText),QProgressBar,QLCDNumber,QFrame, and checkableQGroupBoxsafely. - Choose cleanly between layout-driven containers (
QToolBox,QDockWidget,QMdiArea) and 2D spatialQGraphicsView/QGraphicsScenecanvases.
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 · 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 letsMainWindowbuild on…
GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Cold-Boot Memory Budgets and Choosing the Right Qt 6 Container
- Inside tall configuration pages,
QScrollAreaclips a large child widget through a scrollableviewport().
GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Cold-Boot Memory Budgets and Choosing the Right Qt 6 Container
Figure 5.1a: Cold-boot memory and startup latency savings from lazy QStackedWidget page materialization.
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 · 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 · 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 · 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 · 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 · 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 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Passive Display Hardening, Checkable QGroupBox, and QGraphicsView Overview
Figure 5.1b: Architectural boundaries across Qt 6 display widgets, multi-page containers, and 2D graphics views.
GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# lazy_workbench_containers.cpp
learner@ksa:~/gl-q01/m05-l01$ bat lazy_workbench_containers.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: lazy_workbench_containers.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QDockWidget> 2 │ #include <QFrame> 3 │ #include <QGraphicsRectItem> 4 │ #include <QGraphicsScene> 5 │ #include <QGraphicsView> 6 │ #include <QGroupBox> 7 │ #include <QHBoxLayout> 8 │ #include <QLabel> 9 │ #include <QMainWindow> 10 │ #include <QProgressBar> 11 │ #include <QScrollArea> 12 │ #include <QStackedWidget> 13 │ #include <QVBoxLayout> 14 │ #include <QWidget>───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# QStackedWidget-QScrollArea
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 · 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-screenLazyStackDecktracking both resident page memory and live placehold…
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
8screens of256 KiBeach with only page0eager consumes `…
GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m05-l01$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <algorithm> 2 │ #include <cassert> 3 │ #include <cstddef> 4 │ #include <cstdio> 5 │ #include <functional> 6 │ #include <memory> 7 │ #include <string> 8 │ #include <vector> 9 │ 10 │ struct BuiltPage { 11 │ std::string name; 12 │ std::size_t ram_bytes; 13 │ };───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Verifying Startup Memory Savings, Stub Deletion, and Viewport Expansion
- Run
./verifyand confirm `containers_audit: boot_kib=256 active_kib=512 builds=2 stubs=6 scroll_w=1024 ma…
GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Verifying Startup Memory Savings, Stub Deletion, and Viewport Expansion
- Next, what happens inside an
AlarmsorTelemetrypage when50,000records must be displayed?
GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Verifying Startup Memory Savings, Stub Deletion, and Viewport Expansion
learner@ksa:~/gl-q01/m05-l01$ g++ -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 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Verifying Startup Memory Savings, Stub Deletion, and Viewport Expansion
learner@ksa:~/gl-q01/m05-l01$ strace -e trace=write,exit_group ./verifywrite(1, "containers_audit: boot_kib=256 a"..., 87) = 87exit_group(0) = ?+++ exited with 0 +++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, andQGraphicsViewpartit…
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 · 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 · 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 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Guided Practice
- Add an
evict_inactive_lru()method toLazyStackDeckinverify.cppthat enforces a strict768 KiB(`…
GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Independent Practice
- Write a C++20
PlainVsAutoTextsanitizer check modelingQLabeldefaultAutoTextdetection (<followe…
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.
Correct: B
QLayout / QStackedWidget removal detaches geometry management without destroying the child QWidget or clearing its QObject::parent().
Common misconception: Assuming removeWidget() deletes the removed widget.
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.
Correct: A
Forcing Qt::PlainText bypasses Qt::mightBeRichText() heuristics, improving speed and rendering < / & literally.
Common misconception: Leaving QLabel in Qt::AutoText mode when rendering untrusted or bracketed bus text.
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.
Correct: D
QGraphicsScene uses lightweight non-widget QGraphicsItem objects with BSP spatial indexing and affine view transforms.
Common misconception: Building interactive 2,000-node piping diagrams out of heavyweight QWidget subclasses.
GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Summary
- Registering C++20 page factories in
QStackedWidgetand materializing off-screen diagnostics pages on first visit keeps cold-boot RAM and startup latency within embedded budgets. QScrollAreadefaults towidgetResizable() == false(freezing inner layouts at initial size unless settrue), andQStackedWidget::removeWidget(stub)requires explicitdelete stubto free RAM.- Setting
QLabel::setTextFormat(Qt::PlainText)on live bus strings preventsQt::AutoTextfrom misinterpreting<brackets in telemetry payloads as rich-text HTML tags. QDockWidgetandQMdiAreaorganize multi-pane engineering workbenches (saveState/restoreState), whereasQGraphicsViewindexes thousands of zoomable 2DQGraphicsItemschematics via BSP trees.
GL-Q01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Key takeaways
QScrollAreadefaults towidgetResizable() == false(freezing inner layouts at initial size unless settrue), andQStackedWidget::removeWidget(stub)requires explicitdelete stubto free RAM.- Setting
QLabel::setTextFormat(Qt::PlainText)on live bus strings preventsQt::AutoTextfrom misinterpreting<brackets in telemetry payloads as rich-text HTML tags. QDockWidgetandQMdiAreaorganize multi-pane engineering workbenches (saveState/restoreState), whereasQGraphicsViewindexes thousands of zoomable 2DQGraphicsItemschematics via BSP trees.
GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Model/View vs Item-Widgets: QAbstractTableModel, QListView, QTreeView & Roles
What you'll learn
- Quantify why
QTableWidget,QListWidget, andQTreeWidgetstall at 50,000 records whereasQTableView,QListView, andQTreeViewrender visible viewports inO(visible)work. - Implement
QAbstractTableModel::rowCount,columnCount,headerData, and role-guardeddata()(Qt::DisplayRole,ForegroundRole,UserRole) over a flat C++20std::vector. - Enforce flat-table
parent.isValid() -> 0bounds, unhandled-roleQVariant{}returns, andQListView::setUniformItemSizes(true)optimizations.
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 · 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 x4-column industrial fault log:QTableWidgetexecutes200,000s…
GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Why Item-Based Convenience Widgets Hit a Memory and Latency Wall
- With
QTableView+QAbstractTableModel(orQListView+QAbstractListModel), your C++ data stays once…
GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Why Item-Based Convenience Widgets Hit a Memory and Latency Wall
Figure 5.2a: Memory layout and GUI-thread latency comparison at 50,000 rows x 4 columns.
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 · 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 · 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 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# QModelIndex Lifetimes, Qt::ItemDataRole Facets, and Tree vs Flat Contracts
QModelIndexis a tiny stack value (row(),column(),internalPointer(),model()), never a long-liv…
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::ItemDataRolecleanly separates presentation from typ…
GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# QModelIndex Lifetimes, Qt::ItemDataRole Facets, and Tree vs Flat Contracts
- Finally, note how
QTreeViewgeneralizes tables and lists: every model method receives `const QModelIndex…
GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# QModelIndex Lifetimes, Qt::ItemDataRole Facets, and Tree vs Flat Contracts
Figure 5.2b: Mapping QListView, QTableView, and QTreeView onto QAbstractItemModel virtual contracts.
GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# telemetry_table_model.hpp
learner@ksa:~/gl-q01/m05-l02$ bat telemetry_table_model.hpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: telemetry_table_model.hpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #pragma once 2 │ #include <QAbstractTableModel> 3 │ #include <QColor> 4 │ #include <QHeaderView> 5 │ #include <QListView> 6 │ #include <QString> 7 │ #include <QTableView> 8 │ #include <QVariant> 9 │ #include <cstdint> 10 │ #include <vector> 11 │ 12 │ struct TelemetrySample { 13 │ std::uint64_t timestampMs; 14 │ std::uint16_t channelId;───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# QAbstractTableModel-Roles
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 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Host C++20 Benchmark Contrasting 50,000-Row Virtual Models vs Item Allocation
- In
verify.cpp, we populate50,000contiguousSampleRowstructs (16 byteseach =800 KiB) and meas…
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 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m05-l02$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <algorithm> 2 │ #include <array> 3 │ #include <cassert> 4 │ #include <cstdint> 5 │ #include <cstdio> 6 │ #include <ctime> 7 │ #include <memory> 8 │ #include <string> 9 │ #include <vector> 10 │ 11 │ enum class Role { Display, Foreground, CheckState, UserValue, UserSeverity }; 12 │ 13 │ struct Variant { 14 │ bool valid = false;───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Comparing O(visible) Viewport Latency Against Eager Item Allocation
- Inspect the
./verifyoutput:rows=50000 item_allocs=0renders a25-row (100-cell) viewport straight…
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 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Comparing O(visible) Viewport Latency Against Eager Item Allocation
learner@ksa:~/gl-q01/m05-l02$ g++ -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 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Comparing O(visible) Viewport Latency Against Eager Item Allocation
learner@ksa:~/gl-q01/m05-l02$ strace -e trace=write,exit_group ./verifywrite(1, "model_audit: rows=50000 item_all"..., 81) = 81exit_group(0) = ?+++ exited with 0 +++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
QModelIndexrole queries scalesQTableView, `Q…
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_MONOTONICtimings measure pure C++20 `…
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 · 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 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Guided Practice
- Extend
VirtualTelemetryModelinverify.cppwith aheader_data(int section, Role role)method that ret…
GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Independent Practice
- Implement a two-level hierarchical
DeviceTreeModelin ISO C++20 (parent()andindex()using integer n…
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.
Correct: A
Whenever data(idx, Qt::CheckStateRole) returns a valid QVariant, QStyledItemDelegate paints a checkbox indicator in that cell.
Common misconception: Ignoring the role argument inside QAbstractItemModel::data().
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.
Correct: D
Returning N for a valid parent tells views that every cell contains another N-row child table underneath it.
Common misconception: Ignoring the parent parameter in rowCount() and columnCount().
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.
Correct: C
Uniform/fixed row heights let views multiply rowCount() * rowHeight in O(1) instead of querying sizeHint across 50,000 rows.
Common misconception: Calling ResizeToContents on 50,000-row telemetry tables.
GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Summary
- Convenience widgets (
QTableWidget,QListWidget,QTreeWidget) allocateO(R * C)heap item objects and duplicateQVariantstrings, whereasQTableView,QListView, andQTreeViewquerydata()only for visible viewport cells. QModelIndexis 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::DisplayRoletext,Qt::ForegroundRolecolor,Qt::UserRole + kraw typed integers) and must return emptyQVariant{}for unhandled roles.- A flat
QAbstractTableModelorQAbstractListModelmust return0fromrowCount(parent)wheneverparent.isValid()istrue, whereasQTreeViewmodels encode parent-child pointers viacreateIndex(row, col, ptr).
GL-Q01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Key takeaways
QModelIndexis 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::DisplayRoletext,Qt::ForegroundRolecolor,Qt::UserRole + kraw typed integers) and must return emptyQVariant{}for unhandled roles.- A flat
QAbstractTableModelorQAbstractListModelmust return0fromrowCount(parent)wheneverparent.isValid()istrue, whereasQTreeViewmodels encode parent-child pointers viacreateIndex(row, col, ptr).
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# beginInsertRows Contracts, QSortFilterProxyModel & Custom StyledItemDelegates
What you'll learn
- Bracket structural vector mutations inside inclusive
beginInsertRows/endInsertRowsandbeginRemoveRows/endRemoveRowspairs soQPersistentModelIndexselections stay valid. - Filter and sort models zero-copy via
QSortFilterProxyModel(beginFilterChange/endFilterChange,UserRole) while translating view indices withmapToSource. - Record reversible operator edits on
QUndoStack/QUndoViewand custom-paint cell badges inQStyledItemDelegate::paintwithoutsetIndexWidgetbloat.
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Structural Notification Contracts vs the beginResetModel Anti-Pattern
- When live telemetry appends to
m_rowsat20 Hz, callingbeginResetModel(); endResetModel();tells eve…
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Structural Notification Contracts vs the beginResetModel Anti-Pattern
- Two invariants in
QAbstractItemModelare non-negotiable.
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
acknowledgedflag on rowr—do not touch insert/remove sign…
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Structural Notification Contracts vs the beginResetModel Anti-Pattern
Figure 5.3a: Preserving selection, scroll position, and 60 Hz frame budgets on live filtered tables.
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 · 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 · 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 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# QSortFilterProxyModel Coordinate Mapping, QUndoStack, and Flyweight Delegates
QSortFilterProxyModelwraps a source model to filter rows (filterAcceptsRow) and sort columns without c…
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 · 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,000emb…
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# QSortFilterProxyModel Coordinate Mapping, QUndoStack, and Flyweight Delegates
Figure 5.3b: Exact coordinate rules across QAbstractItemModel notifications, proxies, QUndoStack, and delegates.
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# proxy_delegate_undo.cpp
learner@ksa:~/gl-q01/m05-l03$ bat proxy_delegate_undo.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: proxy_delegate_undo.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QAbstractTableModel> 2 │ #include <QPainter> 3 │ #include <QSortFilterProxyModel> 4 │ #include <QStyledItemDelegate> 5 │ #include <QUndoCommand> 6 │ #include <QUndoStack> 7 │ #include <vector> 8 │ 9 │ struct AlarmEntry { 10 │ int id; 11 │ int severity; // 0=Info, 1=Warn, 2=Critical 12 │ bool acked = false; 13 │ };───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# QSortFilterProxyModel-QUndoStack
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 · 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:PersistentIndexrow shifting…
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 urgentid = 100at row0shift…
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m05-l03$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <cassert> 2 │ #include <cstdio> 3 │ #include <memory> 4 │ #include <vector> 5 │ 6 │ struct Alarm { 7 │ int id; 8 │ int sev; 9 │ bool acked = false; 10 │ }; 11 │ 12 │ class LiveStore { 13 │ public: 14 │ int track_persistent(int row) {───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Verifying Persistent Shifts, Proxy Coordinate Mapping, and Undo History
- Confirm
./verifyoutputsproxy_undo_audit: crit_rows=2 mapped_src=2 redo_acked=1 evicted_handle=-1.
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 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Verifying Persistent Shifts, Proxy Coordinate Mapping, and Undo History
learner@ksa:~/gl-q01/m05-l03$ g++ -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 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Verifying Persistent Shifts, Proxy Coordinate Mapping, and Undo History
learner@ksa:~/gl-q01/m05-l03$ strace -e trace=write,exit_group ./verifywrite(1, "proxy_undo_audit: crit_rows=2 ma"..., 74) = 74exit_group(0) = ?+++ exited with 0 +++GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Proxy Row Mix-Ups, Painter State Leaks, and Half-Open Insert Bounds
- Granular
beginInsertRows/beginRemoveRowsbrackets, zero-copyQSortFilterProxyModelviews, `QUndoStack…
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
QSaveFileconfiguration persistence, premultiplied ARGB…
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 · 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 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Guided Practice
- Extend
ProxyMapinverify.cppwithmap_from_source(int src_row)returning the proxy row index (or `-1…
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Independent Practice
- Complete
lab_m05_table_model_rolesby fixing the three defects instarter/core.cpp: returning empty `Ro…
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.
Correct: D
beginInsertRows must run prior to mutating m_rows, and [first, last] is an inclusive range (6, 6 for a single row at index 6).
Common misconception: Passing half-open [6, 7) bounds or mutating m_rows before beginInsertRows.
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.
Correct: C
View signals report coordinates in the attached model (proxy), which differ from src whenever rows are filtered or sorted.
Common misconception: Indexing a source model with an unmapped proxy row().
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.
Correct: B
setIndexWidget() pins live child QWidget instances onto model indices, defeating Model/View virtualization.
Common misconception: Embedding thousands of QWidget instances into scrolling views via setIndexWidget().
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Lab: lab_m05_table_model_roles
- Implement and verify a bounded-capacity
FaultTableModelandFaultFilterProxywith multi-roledata()d…
Verify: ./check.sh exits 0.
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Summary
beginInsertRows(parent, first, last)andbeginRemoveRows(parent, first, last)take inclusive[first, last]indices BEFORE mutating the backing vector, updatingQPersistentModelIndexselections without resetting scroll state.- A view bound to
QSortFilterProxyModelemits proxyQModelIndexcoordinates that must be translated viaproxy->mapToSource(proxyIdx)before indexing the sourceQAbstractItemModel. QUndoStackandQUndoCommand(undo()/redo(), inspectable viaQUndoView) encapsulate reversible operator table and parameter edits cleanly.- One flyweight
QStyledItemDelegate::paintinstance (painter->save()/restore()) custom-renders visible severity badges with zero extraQWidgetallocations, unlikeQAbstractItemView::setIndexWidget().
GL-Q01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Key takeaways
- A view bound to
QSortFilterProxyModelemits proxyQModelIndexcoordinates that must be translated viaproxy->mapToSource(proxyIdx)before indexing the sourceQAbstractItemModel. QUndoStackandQUndoCommand(undo()/redo(), inspectable viaQUndoView) encapsulate reversible operator table and parameter edits cleanly.- One flyweight
QStyledItemDelegate::paintinstance (painter->save()/restore()) custom-renders visible severity badges with zero extraQWidgetallocations, unlikeQAbstractItemView::setIndexWidget().
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.
- 6.1 QFile, QTextStream & Crash-Atomic QSaveFile Configuration Persistence
- 6.2 Custom QPainter Gauges, Premultiplied ARGB32 & Real-Time QtCharts
- 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 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# QFile, QTextStream & Crash-Atomic QSaveFile Configuration Persistence
What you'll learn
- Explain at the
Linux kernelVFS syscall boundary whyQFile(QIODevice::WriteOnly | QIODevice::Truncate) corrupts live files on power loss whereasQSaveFilestays atomic. - Trace the
openat -> write -> fsync -> renamecommit path ofQSaveFile::commit()and the automaticunlinkrollback ofcancelWriting()and~QSaveFile(). - Serialize UTF-8
QTextStream(QStringConverter::Utf8) andQJsonDocument(QJsonParseError) payloads with all-or-nothing schema validation.
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 Vcabinet disconnect without cli…
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
ext4delayed allocation has not yet flushed dirty page-cache…
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Why Truncate-in-Place Destroys Embedded Configurations on Power Loss
QSaveFileeliminates that window completely.
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Why Truncate-in-Place Destroys Embedded Configurations on Power Loss
Figure 6.1a: Linux kernel VFS syscall comparison between in-place QFile truncation and transactional QSaveFile.
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 · 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 · 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 · 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 declaredprivate!
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# QSaveFile::commit Internals, UTF-8 QTextStream, and QJsonDocument Validation
- Pair
QSaveFilewith clean UTF-8 serializers.
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# QSaveFile::commit Internals, UTF-8 QTextStream, and QJsonDocument Validation
- For human-readable audit exports (
CSVorINI), attachQTextStream stream(&saveFile).
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# QSaveFile::commit Internals, UTF-8 QTextStream, and QJsonDocument Validation
Figure 6.1b: Pairing Qt 6 I/O devices (QFile for reads, QSaveFile for writes) with UTF-8 serializers.
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# atomic_config_persistence.cpp
learner@ksa:~/gl-q01/m06-l01$ bat atomic_config_persistence.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: atomic_config_persistence.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QFile> 2 │ #include <QJsonDocument> 3 │ #include <QJsonObject> 4 │ #include <QJsonParseError> 5 │ #include <QSaveFile> 6 │ #include <QString> 7 │ #include <QStringConverter> 8 │ #include <QTextStream> 9 │ 10 │ struct CalibrationConfig { 11 │ int zeroOffsetKpa = 0; 12 │ int alarmLimitKpa = 420; 13 │ };───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# QSaveFile-QTextStream
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 · 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 POSIXAtomicSaveTransactionmatchingQSaveFile's exact syscall sequence (`o…
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(): scope1commitsv1(40bytes) cleanly, while sc…
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m06-l01$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <cassert> 2 │ #include <cstdio> 3 │ #include <cstdlib> 4 │ #include <fcntl.h> 5 │ #include <string> 6 │ #include <string_view> 7 │ #include <unistd.h> 8 │ 9 │ class AtomicSaveTransaction { 10 │ public: 11 │ explicit AtomicSaveTransaction(std::string target) 12 │ : m_target(std::move(target)), m_tmp(m_target + ".tmp") {} 13 │ 14 │ ~AtomicSaveTransaction() {───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Inspecting the Live Kernel strace Transcript of Commit and Rollback
- Examine the
stracecapture below line by line!
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Inspecting the Live Kernel strace Transcript of Commit and Rollback
- Immediately below it, Transaction
2openscalib.json.tmp, writes"{\"corrupt_half", and calls `unlink…
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$ g++ -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 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Inspecting the Live Kernel strace Transcript of Commit and Rollback
learner@ksa:~/gl-q01/m06-l01$ strace -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") = 0GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Filesystem Mount Boundaries, Missing QTextStream Flushes, and Flash Wear
QSaveFileturns fragile configuration writes into crash-atomic transactions with five lines of C++20.
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 underlyingeMMCcontroller honoring…
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 · 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 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Guided Practice
- Extend
AtomicSaveTransaction::commit()inverify.cppto also `openat(AT_FDCWD, parent_dir, O_RDONLY | O…
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Independent Practice
- Write a C++20 configuration loader with automatic
.bakfallback that verifies a trailingCRC32field in…
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.
Correct: A
QSaveFile's destructor invokes cancelWriting() whenever commit() was not called, discarding the uncommitted .tmp artifact.
Common misconception: Confusing ~QSaveFile() transactional rollback with ~QFile() auto-close.
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.
Correct: D
Atomic rename() only relinks directory entries within a single mounted filesystem.
Common misconception: Assuming rename("/tmp/cfg", "/var/lib/cfg") works atomically across mounts.
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.
Correct: C
Hiding QIODevice::close() prevents accidental migration bugs where QFile::close() code silently skips commit().
Common misconception: Trying to finalize a QSaveFile with close() instead of commit().
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Summary
- Opening an existing configuration file with
QFileandQIODevice::WriteOnly | QIODevice::Truncatezeroes the live inode immediately (O_TRUNC), leaving a0-byte or partial file if power fails mid-write. QSaveFilewrites to a sibling temporary file in the destination directory, flushes storage viafsync(), and atomically replaces the target via POSIXrename()insidecommit().- If
QSaveFileleaves scope without callingcommit()(or aftercancelWriting()),~QSaveFile()closes andunlink()s the temporary file while leaving the previous configuration file untouched. - Qt 6
QTextStreamdefaults toQStringConverter::Utf8(requiring explicitstatus() == QTextStream::Okchecks), whileQJsonDocument::fromJsonpinpoints syntax faults viaQJsonParseError.
GL-Q01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Key takeaways
QSaveFilewrites to a sibling temporary file in the destination directory, flushes storage viafsync(), and atomically replaces the target via POSIXrename()insidecommit().- If
QSaveFileleaves scope without callingcommit()(or aftercancelWriting()),~QSaveFile()closes andunlink()s the temporary file while leaving the previous configuration file untouched. - Qt 6
QTextStreamdefaults toQStringConverter::Utf8(requiring explicitstatus() == QTextStream::Okchecks), whileQJsonDocument::fromJsonpinpoints syntax faults viaQJsonParseError.
GL-Q01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Custom QPainter Gauges, Premultiplied ARGB32 & Real-Time QtCharts
What you'll learn
- Implement custom
QWidget::paintEvent(QPaintEvent *)gauges using logicaltranslate/scaletransforms,ev->region()clipping, andupdate()coalescing. - Prove Porter-Duff
SourceOvercompositing arithmetic onQImage::Format_ARGB32_Premultipliedstatic dial caches without per-pixel alpha division. - Eliminate GUI-thread stalls in real-time
QtCharts(QChart,QLineSeries,QValueAxis) by replacing per-sampleappend()calls with ring-bufferedreplace(QList<QPointF>).
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 · 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 · 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 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Premultiplied Alpha Physics and the paintEvent Backing-Store Contract
Figure 6.2a: Eliminating per-pixel division and per-sample chart re-layout on embedded Linux HMIs.
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 · 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 · 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 · 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 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# High-Rate Real-Time Waveforms in QtCharts: Why replace Beats append
- Every single
append(x, y)emitspointAdded(int), marks theQGraphicsScenedirty, and triggers chart g…
GL-Q01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# High-Rate Real-Time Waveforms in QtCharts: Why replace Beats append
- Pair
replace()with threeQCharthardening settings: call `chart->setAnimationOptions(QChart::NoAnimati…
GL-Q01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# High-Rate Real-Time Waveforms in QtCharts: Why replace Beats append
Figure 6.2b: Bit-level premultiplied ARGB32 layout and QtCharts real-time series architecture.
GL-Q01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# gauge_and_chart_panel.cpp
learner@ksa:~/gl-q01/m06-l02$ bat gauge_and_chart_panel.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: gauge_and_chart_panel.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <QtCharts/QChart> 2 │ #include <QtCharts/QChartView> 3 │ #include <QtCharts/QLineSeries> 4 │ #include <QtCharts/QValueAxis> 5 │ #include <QHBoxLayout> 6 │ #include <QImage> 7 │ #include <QList> 8 │ #include <QPaintEvent> 9 │ #include <QPainter> 10 │ #include <QPointF> 11 │ #include <QWidget> 12 │ #include <algorithm> 13 │ 14 │ class RadialPressureGauge final : public QWidget {───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# QPainter-QtCharts
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 · 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 · 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 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m06-l02$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <algorithm> 2 │ #include <array> 3 │ #include <cassert> 4 │ #include <cmath> 5 │ #include <cstdint> 6 │ #include <cstdio> 7 │ #include <ctime> 8 │ #include <numbers> 9 │ #include <vector> 10 │ 11 │ struct Rect { 12 │ int x, y, w, h; 13 │ constexpr bool contains(int px, int py) const noexcept { 14 │ return px >= x && px < (x + w) && py >= y && py < (y + h);───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Verifying ARGB32 Blending, Clip Isolation, and QtCharts Batch Speedup
- Confirm
./verifyoutputsinside=0xFF772326 clipped=0xFF102030 tip=(50,15)along withappend_nsmore t…
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 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Verifying ARGB32 Blending, Clip Isolation, and QtCharts Batch Speedup
learner@ksa:~/gl-q01/m06-l02$ g++ -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 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Verifying ARGB32 Blending, Clip Isolation, and QtCharts Batch Speedup
learner@ksa:~/gl-q01/m06-l02$ strace -e trace=write,exit_group ./verifywrite(1, "render_audit: inside=0xFF76232B "..., 98) = 98exit_group(0) = ?+++ exited with 0 +++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 · 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 · 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 · 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 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Guided Practice
- Add a channel-invariant verifier
is_valid_premul(uint32_t px)toverify.cppchecking thatpr <= a, `p…
GL-Q01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Independent Practice
- Write a fixed-capacity power-of-two
WaveformRing<512>in C++20 supportingpush_isr_sample(float)and `c…
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.
Correct: D
Qt's software backing store composites natively in premultiplied ARGB32 using SIMD shift-and-add operations.
Common misconception: Choosing Format_ARGB32 out of habit and paying hidden per-pixel conversion costs.
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.
Correct: C
QPainter integer arc functions measure angles in sixteenths of a degree (16 == 1 deg, 5760 == 360 deg).
Common misconception: Passing unscaled whole degrees to QPainter::drawArc().
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.
Correct: B
replace(const QList<QPointF> &) swaps the vertex buffer and emits pointsReplaced() once per frame instead of 1,000 pointAdded updates per second.
Common misconception: Calling QLineSeries::append() per sample on high-frequency real-time streams.
GL-Q01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Summary
- All
QWidgetdrawing must execute insidepaintEvent(QPaintEvent *)(scheduled asynchronously viaupdate()), honoringevent->region()dirty clip bounds on the window backing store. QImage::Format_ARGB32_Premultipliedpre-scales RGB channels byalpha / 255, lettingQPainterPorter-DuffSourceOverblendout = src + dst * (255 - a) / 255without per-pixel division.- Caching static gauge bezels and tick marks into a
Format_ARGB32_PremultipliedQImageonresizeEventavoids repeating trigonometric tick strokes on every 60 Hz needle update. - In
QtCharts, callingQLineSeries::append(x, y)at1 kHztriggers1,000per-point signal/layout passes per second, whereas buffering samples and callingseries->replace(points)at30 Hzemits once per frame.
GL-Q01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Key takeaways
QImage::Format_ARGB32_Premultipliedpre-scales RGB channels byalpha / 255, lettingQPainterPorter-DuffSourceOverblendout = src + dst * (255 - a) / 255without per-pixel division.- Caching static gauge bezels and tick marks into a
Format_ARGB32_PremultipliedQImageonresizeEventavoids repeating trigonometric tick strokes on every 60 Hz needle update. - In
QtCharts, callingQLineSeries::append(x, y)at1 kHztriggers1,000per-point signal/layout passes per second, whereas buffering samples and callingseries->replace(points)at30 Hzemits once per frame.
GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Automated HMI Verification: QTest, QSignalSpy & Headless Offscreen TAP 13
What you'll learn
- Drive interactive widgets headlessly under
QT_QPA_PLATFORM=offscreenusingQTest::mouseClick,QTest::keyClicks, and data-driven_data()/QFETCHtables. - Verify exact signal emission counts, argument payloads, and asynchronous timer slots using
QSignalSpyandspy.wait()/QTRY_COMPAREinstead of blockingsleep. - Emit machine-parsable
TAP version 13test transcripts via-o -,tapfor automated CI gating.
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
QtWidgetsbinaries require anX11or…
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 msdebounceQTimerafter an operator clicksArm—e…
GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Headless Offscreen QPA Execution and Why Thread Sleeps Starve QTimers
QSignalSpy::wait(200)andQTRY_COMPARE(spy.count(), 1)spin a nestedQEventLoopuntil the signal arri…
GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Headless Offscreen QPA Execution and Why Thread Sleeps Starve QTimers
Figure 6.3a: End-to-end headless QtWidgets verification from synthetic input injection to TAP 13 CI gates.
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 · 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 · 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 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Data-Driven _data Matrices, Synthetic Input Injection, and TAP 13 CI Gates
Qt6::Testpairs private test slots (void interlockMatrix()) with companion data-generator slots (`void…
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 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Data-Driven _data Matrices, Synthetic Input Injection, and TAP 13 CI Gates
- Pass
-o -,tapon the CI command line soQTestemitsTAP version 13(`ok 1 - interlockMatrix(below_lim…
GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Data-Driven _data Matrices, Synthetic Input Injection, and TAP 13 CI Gates
Figure 6.3b: Core Qt6::Test primitives for deterministic widget, signal, timer, and pixel regression suites.
GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# tst_hmi_panel.cpp
learner@ksa:~/gl-q01/m06-l03$ bat tst_hmi_panel.cpp───────┬───────────────────────────────────────────────────────────────────────────────── │ File: tst_hmi_panel.cpp───────┼───────────────────────────────────────────────────────────────────────────────── 1 │ #include <QLineEdit> 2 │ #include <QPushButton> 3 │ #include <QSignalSpy> 4 │ #include <QTimer> 5 │ #include <QtTest> 6 │ 7 │ class DebouncedSetpointBox final : public QWidget { 8 │ Q_OBJECT 9 │ public: 10 │ explicit DebouncedSetpointBox(QWidget *parent = nullptr) : QWidget(parent) { 11 │ m_edit = new QLineEdit(this); 12 │ m_applyBtn = new QPushButton(tr("Apply"), this); 13 │ m_applyBtn->setMinimumSize(44, 44); 14 │ m_applyBtn->setAutoRepeat(false);───────┴─────────────────────────────────────────────────────────────────────────────────GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# QTest-QSignalSpy
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 · 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++20MiniEventLoop, aDebouncedPanelscheduling asynchronous15 msc…
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.cppalso proves the thread-sleep anti-pattern directly: advancing wall wait WITHOUT pum…
GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# verify.cpp
learner@ksa:~/gl-q01/m06-l03$ bat verify.cpp───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.cpp───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <algorithm> 2 │ #include <cassert> 3 │ #include <cstdio> 4 │ #include <functional> 5 │ #include <string> 6 │ #include <tuple> 7 │ #include <vector> 8 │ 9 │ class MiniEventLoop { 10 │ public: 11 │ void single_shot(int delay_ms, std::function<void()> cb) { 12 │ m_timers.push_back({m_now_ms + delay_ms, std::move(cb)}); 13 │ } 14 │ void step_ms(int dt_ms) {───────┴────────────────────────────────────────────────────────────────────────────────GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Verifying Data-Driven Hysteresis Rows and Event-Pumping SignalSpy Output
- Confirm
./verifyprintsqtest_audit: tap_rows=4/4 spy_wait_pumped=1 platform=offscreen.
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 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Verifying Data-Driven Hysteresis Rows and Event-Pumping SignalSpy Output
learner@ksa:~/gl-q01/m06-l03$ g++ -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 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Verifying Data-Driven Hysteresis Rows and Event-Pumping SignalSpy Output
learner@ksa:~/gl-q01/m06-l03$ strace -e trace=write,exit_group ./verifywrite(1, "qtest_audit: tap_rows=4/4 spy_wa"..., 63) = 63exit_group(0) = ?+++ exited with 0 +++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 · 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 acrossQThreadworker pipelines…
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 · 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 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Guided Practice
- Add a fifth row
"invalid_out_of_range"(inputs = {"999", "50"}) torowsinverify.cppwhere `mouse_…
GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Independent Practice
- Complete the
GL-Q01Capstone Project (lab_m06_qpainter_gauge_qtest) by repairing the three starter defe…
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.
Correct: C
QT_QPA_PLATFORM=offscreen activates Qt's headless RAM surface QPA plugin, and -o -,tap directs TAP 13 output to stdout (-).
Common misconception: Assuming QtWidgets unit tests require an X11, Xvfb, or Wayland server.
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.
Correct: B
Single-threaded event loops only dispatch QTimer callbacks while pumping events (spy.wait(), QTRY_COMPARE, or QTest::qWait()).
Common misconception: Blocking the GUI event-loop thread with sleep_for while waiting for event-driven callbacks.
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.
Correct: A
Synthetic input events traverse the full QWidget enablement and filter chain, catching broken UI gates that direct method calls bypass.
Common misconception: Testing internal helper methods while leaving broken button enablement or filters undetected.
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-stylefsync+renameca…
Verify: ./check.sh exits 0.
GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Summary
- Setting
QT_QPA_PLATFORM=offscreenruns fullQtWidgetslayouts, input dispatch, andQPaintergrab()rasterization in headless Linux CI containers without X11 or Wayland. QTest::mouseClickandQTest::keyClickssynthesize realistic user events throughQWidgetevent filters and button interlocks, paired with_data()/QFETCHboundary matrices.QSignalSpyrecords emitted signal argument lists (spy.count(),spy.at(i)), whilespy.wait()andQTRY_COMPAREpump the thread event loop instead of deadlocking timers withsleep.- Passing
-o -,tapto a compiledQTestbinary formats stdout as standardTAP version 13(ok/not ok+ YAML diagnostics) for CI pipelines.
GL-Q01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Key takeaways
QTest::mouseClickandQTest::keyClickssynthesize realistic user events throughQWidgetevent filters and button interlocks, paired with_data()/QFETCHboundary matrices.QSignalSpyrecords emitted signal argument lists (spy.count(),spy.at(i)), whilespy.wait()andQTRY_COMPAREpump the thread event loop instead of deadlocking timers withsleep.- Passing
-o -,tapto a compiledQTestbinary formats stdout as standardTAP version 13(ok/not ok+ YAML diagnostics) for CI pipelines.