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.
Print this handbook or save as PDF (A4 or Letter) for offline engineering reference. Terminal listings convert automatically to crisp white ink-saving frames in print.
m01/
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.
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.
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 comparisons under strict ISO C++20 (-std=c++20). Legacy qmake .pro projects and older CMake files often rely on directory-wide INCLUDEPATH +=, include_directories(), or add_definitions(). Those global mutations leak widget macros, -fPIC settings, and relaxed warning flags into pure C++20 protocol libraries and unit-test binaries in the same workspace.
Before g++ compiles any QObject translation unit, three code generators execute inside the build graph. moc scans class declarations for Q_OBJECT or Q_GADGET and emits C++ meta-object tables; uic lowers Designer .ui XML layouts into ui_*.h headers; and rcc packs .qrc icons or shaders into static C++ byte arrays. Understanding exactly where CMake places those generated files eliminates baffling undefined reference to vtable link failures during bring-up.
Figure 1.1a. Target-scoped CMake properties isolate , uic, and rcc generation per binary while keeping strict ISO C++20 flags off vendor headers.
mental model: 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.
definition ( and Imported CMake Targets): 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.
- Step 1. Lock CXX_STANDARD 20, CXX_STANDARD_REQUIRED ON, and CXX_EXTENSIONS OFF directly on the HMI target.
- Step 2. Enable AUTOMOC, AUTOUIC, and AUTORCC on the target and list headers explicitly inside add_executable.
- Step 3. Replace mega-header #include <QtWidgets> directives with class forward declarations in every .hpp file.
- Step 4. Append #include '<stem>.moc' at the end of any .cpp file that defines a private Q_OBJECT helper class.
Figure 1.1b. Use target-scoped CMake properties, forward declarations, and explicit .moc includes.
Inside Autogen Artifact Layout and Header Dependency Fan-Out
When Ninja or GNU Make builds target ksa_hmi, CMake creates ksa_hmi_autogen/include/ for generated headers (ui_panel_window.h and inline panel_window.moc) plus ksa_hmi_autogen/mocs_compilation.cpp, which #includes moc_panel_window.cpp for every header-declared Q_OBJECT. Because mocs_compilation.cpp is a separate translation unit, any helper class PollWorker : public QObject { Q_OBJECT }; written privately inside panel_window.cpp is completely invisible to mocs_compilation.cpp. Including "panel_window.moc" at the bottom of panel_window.cpp inlines that generated moc body directly where PollWorker is complete.
Header discipline matters just as much on multi-core build servers and embedded cross-toolchains. Pulling #include <QtWidgets> inside panel_window.hpp forces the C++ preprocessor to open hundreds of indirect headers—exceeding 150,000 preprocessed lines—in every .cpp file that touches PanelWindow. Because sizeof(QPushButton *) is always 8 bytes on x86_64 and 4 bytes on 32-bit ARMv7-A, forward-declaring class QPushButton; in panel_window.hpp keeps header parsing tiny and confines widget header dependencies to panel_window.cpp.
Figure 1.1b. Separating header moc compilation, inline .moc includes, ui_*.h forms, and qrc_*.cpp arrays prevents mystery link errors.
| Build Mechanism | Legacy .pro / Global CMake | Modern Target CMake 3.28+ | Impact on HMI Codebase |
|---|---|---|---|
| Standard Pinning | CMAKE_CXX_STANDARD mutated globally with GNU extensions | CXX_STANDARD 20, CXX_STANDARD_REQUIRED ON, CXX_EXTENSIONS OFF | Identical ISO C++20 semantics across GCC and Clang |
| Include & Flag Scope | include_directories() leaks paths to all subdirectories | target_link_libraries(app PRIVATE Qt6::Widgets) | Unit tests and core libraries stay free of GUI flags |
| Meta-Object Wiring | Manual qt_wrap_cpp() lists drifting out of sync | AUTOMOC ON + explicit .hpp files in add_executable | Zero stale moc tables when adding Q_OBJECT |
| Widget Header Style | #include <QtWidgets> inside public .hpp headers | Forward-declare class QLabel; in .hpp; include in .cpp | Cuts incremental compile fan-out by an order of magnitude |
learner@ksa:~/gl-q01/m01-l01$ bat -H 6 -H 14 CMakeLists.txt File: CMakeLists.txt cmake_minimum_required(VERSION 3.28) project(ksa_hmi VERSION 1.0.0 LANGUAGES CXX) find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets Test) add_executable(ksa_hmi src/main.cpp src/panel_window.hpp src/panel_window.cpp src/panel_window.ui resources/icons.qrc ) set_target_properties(ksa_hmi PROPERTIES CXX_STANDARD 20 CXX_STANDARD_REQUIRED ON CXX_EXTENSIONS OFF AUTOMOC ON AUTOUIC ON AUTORCC ON ) target_compile_options(ksa_hmi PRIVATE -Wall -Wextra -Werror -pedantic ) target_link_libraries(ksa_hmi PRIVATE Qt6::Core Qt6::Gui Qt6::Widgets )- Listing src/panel_window.hpp and .ui/.qrc explicitly gives cmake_autogen an exact dependency manifest.
- CXX_STANDARD_REQUIRED ON plus CXX_EXTENSIONS OFF guarantees strict -std=c++20 without -std=gnu++20 drift.
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. DIAGNOSTICS "undefined reference to vtable for <Class>": 1. Header was added with Q_OBJECT without re-running CMake / autogen scan. 2. Private Q_OBJECT in <stem>.cpp is missing #include "<stem>.moc". Kernel Systems Academy Lesson 1.1 cmake-qt(7) GL-Q01 quick reference · full manual page: man 7 cmake-qt 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_autogen routing rule and header fan-out invariant in pure ISO C++20. In verify.cpp below, audit_cmake_target() inspects a target's standard flags and source list: it routes header Q_OBJECT declarations to mocs_compilation.cpp, requires a matching #include "<stem>.moc" whenever Q_OBJECT appears in a .cpp file, and rejects GNU extension drift.
Second, estimate_preprocessed_kloc() models a 6-unit HMI project comparing a header that includes <QtWidgets> (~140 kLOC preprocessed per client .cpp) against a forward-declared header (~4 kLOC per client .cpp, plus <QtLabel>/<QPushButton> only inside the widget's own implementation unit). Host execution proves our build-graph rules deterministically before cross-compiling against a target ARMv7-A Qt 6 sysroot.
learner@ksa:~/gl-q01/m01-l01$ bat -H 28 -H 48 verify.cpp File: verify.cpp #include <cassert> #include <cstdio> #include <string> #include <string_view> #include <vector> namespace hmi_build { struct SourceUnit { std::string path; bool has_q_object; bool has_dot_moc_include; bool pulls_umbrella_qtwidgets; int client_tus; }; struct AuditReport { int moc_header_jobs = 0; int moc_inline_jobs = 0; int missing_moc_errors = 0; int umbrella_violations = 0; int estimated_kloc = 0; }; static bool ends_with(std::string_view s, std::string_view suffix) noexcept { return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix; } static AuditReport audit_cmake_target(const std::vector<SourceUnit> &units, int cxx_std, bool std_required, bool gnu_extensions) { assert(cxx_std >= 20 && std_required && !gnu_extensions); AuditReport rep{}; for (const auto &u : units) { const bool is_hdr = ends_with(u.path, ".hpp"); const bool is_src = ends_with(u.path, ".cpp"); if (is_hdr) { if (u.pulls_umbrella_qtwidgets) { ++rep.umbrella_violations; rep.estimated_kloc += u.client_tus * 140; } else { rep.estimated_kloc += u.client_tus * 4 + 18; } } if (!u.has_q_object) { continue; } if (is_hdr) { ++rep.moc_header_jobs; } else if (is_src) { if (u.has_dot_moc_include) { ++rep.moc_inline_jobs; } else { ++rep.missing_moc_errors; } } } return rep; } } // namespace hmi_build int main() { using hmi_build::SourceUnit; const std::vector<SourceUnit> clean_hmi = { {"panel_window.hpp", true, false, false, 6}, {"panel_window.cpp", true, true, false, 0}, {"alarm_strip.hpp", true, false, false, 6}, {"main.cpp", false, false, false, 0}, }; const auto ok = hmi_build::audit_cmake_target(clean_hmi, 20, true, false); assert(ok.moc_header_jobs == 2 && ok.moc_inline_jobs == 1); assert(ok.missing_moc_errors == 0 && ok.umbrella_violations == 0); const std::vector<SourceUnit> legacy_broken = { {"panel_window.hpp", true, false, true, 6}, {"panel_window.cpp", true, false, false, 0}, {"alarm_strip.hpp", true, false, true, 6}, }; const auto bad = hmi_build::audit_cmake_target(legacy_broken, 20, true, false); assert(bad.missing_moc_errors == 1 && bad.umbrella_violations == 2); assert(bad.estimated_kloc > ok.estimated_kloc * 10); std::printf("AUTOMOC clean(hdr=%d inline=%d err=%d kloc=%d) " "broken(err=%d umbrella=%d kloc=%d)\n", ok.moc_header_jobs, ok.moc_inline_jobs, ok.missing_moc_errors, ok.estimated_kloc, bad.missing_moc_errors, bad.umbrella_violations, bad.estimated_kloc); return 0; }- Asserts strict ISO C++20 (cxx_std >= 20, std_required == true, gnu_extensions == false) before scanning units.
- Routes .hpp Q_OBJECT classes to mocs_compilation.cpp and flags .cpp Q_OBJECT classes missing #include '*.moc'.
Inspecting Autogen Audit Metrics and System Call Output
Confirm that ./verify prints clean(hdr=2 inline=1 err=0 kloc=84) versus broken(err=1 umbrella=2 kloc=1680) and exits with status 0. Replacing two <QtWidgets> header includes with forward declarations across 6 client translation units drops modeled preprocessor work from 1680 kLOC to 84 kLOC—a 20x reduction—while catching the missing panel_window.moc include before link time.
Inspect the strace output below as well: the compiled C++20 binary flushes its formatted summary in one write(1, ...) system call and terminates via exit_group(0) without touching external environment files, making build-hygiene linters fast enough to run on every Git hook.
learner@ksa:~/gl-q01/m01-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m01-l01./verifyAUTOMOC clean(hdr=2 inline=1 err=0 kloc=84) broken(err=1 umbrella=2 kloc=1680)learner@ksa:~/gl-q01/m01-l01learner@ksa:~/gl-q01/m01-l01strace -e trace=write,exit_group ./verifywrite(1, "AUTOMOC clean(hdr=2 inline=1 err"..., 79) = 79exit_group(0) = ?+++ exited with 0 +++Build-Graph and Meta-Object Linker Pitfalls
Whenever ld fails with undefined reference to vtable for MyWidget or undefined reference to MyWidget::staticMetaObject, resist deleting your entire build directory blindly. Trace whether AUTOMOC saw the header in target sources, whether Q_OBJECT was added to an existing header without CMake re-scanning dependencies, or whether a .cpp-private Q_OBJECT omitted its trailing .moc include.
With strict -std=c++20, PRIVATE warning flags, imported Qt6::* targets, and forward-declared headers locked in place, our translation units are clean. In Lesson 1.2, we move from build-time compilation units to runtime C++20 move semantics and QObject parent-child ownership trees.
Adding Q_OBJECT to an Existing Header Without Triggering AUTOMOC Re-Scan:
- Symptom: Adding
Q_OBJECTto a previously plainclass StatusCard : public QWidgetcompilesstatus_card.cpp.ocleanly, then fails at link time withundefined reference to vtable for StatusCard. - Root Cause: Declaring
Q_OBJECTinjects virtual declarations (metaObject(),qt_metacall()) whose out-of-line definitions live only insidemoc_status_card.cpp; if the header was omitted fromadd_executableor build stamps were bypassed,mocnever emitted those bodies. - Fix: List every
.hppfile explicitly inadd_executable/add_libraryalongside.cppfiles and re-runcmake --buildso<target>_autogenregeneratesmocs_compilation.cpp.
Attaching -Werror with PUBLIC Visibility on Shared HMI Libraries:
- Symptom: Upgrading GCC on a developer workstation breaks third-party consumers or generated test harnesses with
-Werror=deprecated-declarationsinside external headers. - Root Cause: Passing
-Wall -Wextra -WerrorunderPUBLICorINTERFACEintarget_compile_optionsforces strict warning-as-error flags onto every downstream consumer target. - Fix: Scope strict warning flags (
-Wall -Wextra -Werror -pedantic) asPRIVATEon each owned target and ensure external SDK paths enter asSYSTEMinterface includes (whichQt6::*imported targets do automatically).
Guided Practice
Extend SourceUnit in verify.cpp with a boolean in_target_sources field and verify what happens when a header named telemetry_dialog_p.hpp (whose stem differs from telemetry_dialog.cpp) carries Q_OBJECT while in_target_sources == false. Why can AUTOMOC auto-discover telemetry_dialog.hpp from telemetry_dialog.cpp by stem matching yet miss telemetry_dialog_p.hpp unless the header is listed explicitly in add_executable?
Independent Practice
Audit an existing C++ or qmake .pro HMI directory layout and draft a clean CMakeLists.txt splitting pure C++20 protocol parsing (libprotocol, linking zero Qt libraries) from the GUI executable (ksa_hmi, linking libprotocol and Qt6::Widgets with PRIVATE visibility). Verify with Verify rules that libprotocol carries zero AUTOMOC overhead.
Verification Checks
? check 1 · 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?
- [ ] Add
#include <QtWidgets>at line 1 ofpoller.cppto pre-instantiate allQObjecttables. - [x] Append
#include "poller.moc"at the bottom ofpoller.cppafterPollWorkeris complete. - [ ] Set
CXX_EXTENSIONS ONsog++synthesizes a weak fallbackvtableinsidepoller.cpp.o. - [ ] Change
target_link_librariesfromPRIVATEtoPUBLICsomocs_compilation.cppexportspoller.cpp.
Answer: Append #include "poller.moc" at the bottom of poller.cpp after PollWorker is complete.
Why: 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.
? check 2 · Why should panel_window.hpp write class QPushButton; instead of #include <QtWidgets> when PanelWindow only stores QPushButton *m_armButton;?
- [x] Every object pointer has fixed ABI size, so forward-declaring avoids parsing hundreds of widget headers in client
.cppfiles. - [ ] Including
<QtWidgets>in a header disablesCMAKE_AUTOMOCscanning on that header'sQ_OBJECTmacro. - [ ] Forward declarations allow
PanelWindowto embedQPushButtonby value without knowingsizeof(QPushButton). - [ ]
Qt6::Widgetsforbids including<QPushButton>inside.cppfiles unless forward-declared first.
Answer: Every object pointer has fixed ABI size, so forward-declaring avoids parsing hundreds of widget headers in client .cpp files.
Why: 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.
? check 3 · Which CMake target property trio enforces strict ISO C++20 without GNU extensions on ksa_hmi?
- [ ]
AUTOMOC ON,AUTOUIC ON, andAUTORCC ON, because Qt 6.8 forces-std=c++20automatically. - [ ]
CXX_STANDARD 20withCXX_EXTENSIONS ON, which disables non-ISO GCC keywords. - [ ]
CXX_STANDARD 20alone withCXX_STANDARD_REQUIRED OFFso older compilers warn cleanly. - [x]
CXX_STANDARD 20,CXX_STANDARD_REQUIRED ON, andCXX_EXTENSIONS OFF.
Answer: CXX_STANDARD 20, CXX_STANDARD_REQUIRED ON, and CXX_EXTENSIONS OFF.
Why: 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.
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.
Step sequence — frame strip: steps_m01_l01
Lock CXX_STANDARD 20, CXX_STANDARD_REQUIRED ON, and CXX_EXTENSIONS OFF directly on the HMI target.
reveals: step1
highlights: step1
Enable AUTOMOC, AUTOUIC, and AUTORCC on the target and list headers explicitly inside add_executable.
reveals: step2
highlights: step2
Replace mega-header #include <QtWidgets> directives with class forward declarations in every .hpp file.
reveals: step3
highlights: step3
Append #include '<stem>.moc' at the end of any .cpp file that defines a private Q_OBJECT helper class.
reveals: step4
highlights: step4
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.
Two Competing Lifetime Models Inside One C++20 Binary
Modern ISO C++20 centers memory safety on lexical (Resource Acquisition Is Initialization) and std::unique_ptr<T>: every heap object or POSIX file descriptor has a single owning variable whose destructor releases the resource deterministically when scope unwinds. Qt's QObject hierarchy predates C++11 move semantics and solves deep UI trees with an intrusive parent-child graph: passing this into new QLabel(tr("Ready"), this) appends the new child's this pointer into the parent's QObjectPrivate::children vector.
Collision occurs when engineers mix automatic stack lifetimes or std::unique_ptr with QObject parenting carelessly. C++ destroys local stack variables in strict reverse declaration order. If you write QLabel badge; QWidget panel; badge.setParent(&panel);, panel was constructed second and therefore unwinds FIRST—causing ~QWidget() to execute delete &badge on a stack address! Reconciling C++20 RAII with QObject trees requires one unambiguous ownership rule per allocation.
Figure 1.2a. Every QObject with a non-null parent must be heap-allocated; non-QObject descriptors belong in Rule-of-Five RAII guards.
mental model: 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.
definition (RAII, , and Q_DISABLE_COPY_MOVE): 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.
- Step 1. Wrap POSIX file descriptors or buffers in a Rule-of-Five guard that neutralizes moved-from state to -1.
- Step 2. Allocate child widgets via new with this as parent, keeping non-owning raw pointers as class members.
- Step 3. Verify that derived member destructors never delete a child that base ~QObject() also owns.
- Step 4. Keep parentless root QObjects on main()'s stack or inside std::unique_ptr for deterministic shutdown.
Figure 1.2b. Use Rule-of-Five/unique_ptr for roots and OS handles; use heap + parent this for child QObjects.
Destructor Execution Sequence Across Derived Members and QObjectPrivate
Let us trace the exact ISO C++20 teardown sequence of hmi::AlarmBanner in panel_owner.cpp below. When AlarmBanner is destroyed, the compiler executes ~AlarmBanner()'s body first, then destroys non-static data members in reverse declaration order (m_ackBtn, m_status, m_buzzer), and ONLY THEN invokes base destructors ~QWidget() and ~QObject(). Because m_ackBtn and m_status are raw pointers, destroying those pointer variables does nothing; ~FdGuard() closes the buzzer descriptor once; and ~QObject() calls d->deleteChildren() to delete the heap QVBoxLayout, QLabel, and QPushButton.
Now imagine what happens if an engineer mistakenly declares std::unique_ptr<QLabel> m_status initialized with new QLabel(this)! During ~AlarmBanner(), ~unique_ptr() runs first and deletes the QLabel, whose ~QObject() detaches it from this. That looks lucky—until another child's destructor (or ~QWidget() focus cleanup) touches a sibling or layout expecting parent-driven teardown, or until a parent deletes the child first while unique_ptr still holds the raw address (double free!). Never split ownership of one allocation between two owners.
Figure 1.2b. Derived members unwind before ~QObject(), explaining why raw child pointers pair cleanly with parent-owned heap widgets.
| Resource Category | Correct C++20 / Qt 6 Owner | Pointer Type Stored | Why Alternatives Fail |
|---|---|---|---|
Child QWidget / QObject | Heap new T(..., this) (QObject parent) | Raw T * or QPointer<T> | std::unique_ptr<T> creates dual-owner double-delete risk |
Root QMainWindow / Headless Service | Stack variable in main() or std::unique_ptr<T> | Value or std::unique_ptr<T> | Raw new without parent leaks if an early return exits |
POSIX fd, mmap, or sqlite3 * | Rule-of-Five RAII guard or custom-deleter unique_ptr | By-value guard member (Rule of Zero) | QObject tree only deletes QObject * subclasses |
Modal Stack QDialog With Parent | Declared AFTER parent on stack (or heap WA_DeleteOnClose) | Local automatic QDialog dlg(&win) | Declaring dlg BEFORE win makes ~win() delete stack memory |
learner@ksa:~/gl-q01/m01-l02$ bat -H 19 -H 48 panel_owner.cpp File: panel_owner.cpp #include <QLabel> #include <QPushButton> #include <QVBoxLayout> #include <QWidget> #include <unistd.h> #include <utility> namespace hmi { class FdGuard { public: explicit FdGuard(int fd = -1) noexcept : m_fd(fd) {} ~FdGuard() { reset(); } FdGuard(const FdGuard &) = delete; FdGuard &operator=(const FdGuard &) = delete; FdGuard(FdGuard &&other) noexcept : m_fd(std::exchange(other.m_fd, -1)) {} FdGuard &operator=(FdGuard &&other) noexcept { if (this != &other) { reset(); m_fd = std::exchange(other.m_fd, -1); } return *this; } void reset(int fd = -1) noexcept { if (m_fd >= 0) { ::close(m_fd); } m_fd = fd; } int get() const noexcept { return m_fd; } private: int m_fd; }; class AlarmBanner final : public QWidget { Q_OBJECT public: explicit AlarmBanner(FdGuard buzzerFd, QWidget *parent = nullptr) : QWidget(parent), m_buzzer(std::move(buzzerFd)), m_status(new QLabel(tr("Nominal"), this)), m_ackBtn(new QPushButton(tr("Acknowledge"), this)) { auto *layout = new QVBoxLayout(this); layout->addWidget(m_status); layout->addWidget(m_ackBtn); } private: FdGuard m_buzzer; QLabel *m_status; QPushButton *m_ackBtn; }; } // namespace hmi- std::exchange(other.m_fd, -1) steals the descriptor atomically in C++ semantics and leaves other inert.
- Passing 'this' attaches QLabel and QPushButton to QObject's child tree while AlarmBanner follows Rule of Zero.
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. HAZARDS Never parent a stack-allocated QObject onto a parent whose lifetime ends first. Kernel Systems Academy Lesson 1.2 QObject-ownership(3qt) GL-Q01 quick reference · full manual page: man 3qt QObject-ownership Proving RAII Move Semantics and Tree Unwinding in Host C++20
In verify.cpp, we build hmi::MoveHandle and an intrusive hmi::ObjectNode tree in strict ISO C++20 to verify four runtime invariants: (1) moving h1 into h2 and executing a self-move assignment closes the underlying descriptor exactly once; (2) deleting a heap child (early) ahead of its parent unlinks early cleanly; (3) destroying root sweeps remaining heap children in deterministic reverse order; and (4) parenting a stack node onto a shorter-lived stack parent triggers our explicit invalid-delete detector.
Study lines 47-56 of verify.cpp: popping child from m_children and setting child->m_parent = nullptr BEFORE delete child mirrors Qt's QObjectPrivate::deleteChildren() implementation so child destructors never scan or mutate a half-destroyed parent vector.
learner@ksa:~/gl-q01/m01-l02$ bat -H 22 -H 55 verify.cpp File: verify.cpp #include <algorithm> #include <cassert> #include <cstdio> #include <memory> #include <string> #include <utility> #include <vector> namespace hmi { class MoveHandle { public: MoveHandle(int fd, int *closes) noexcept : m_fd(fd), m_closes(closes) {} ~MoveHandle() { reset(); } MoveHandle(const MoveHandle &) = delete; MoveHandle &operator=(const MoveHandle &) = delete; MoveHandle(MoveHandle &&o) noexcept : m_fd(std::exchange(o.m_fd, -1)), m_closes(std::exchange(o.m_closes, nullptr)) {} MoveHandle &operator=(MoveHandle &&o) noexcept { if (this != &o) { reset(); m_fd = std::exchange(o.m_fd, -1); m_closes = std::exchange(o.m_closes, nullptr); } return *this; } void reset() noexcept { if (m_fd >= 0 && m_closes) { ++(*m_closes); } m_fd = -1; } private: int m_fd; int *m_closes; }; class ObjectNode { public: ObjectNode(std::string name, ObjectNode *parent, bool heap_allocated, std::vector<std::string> &log, int &stack_delete_faults) : m_name(std::move(name)), m_heap(heap_allocated), m_log(log), m_faults(stack_delete_faults) { set_parent(parent); } ObjectNode(const ObjectNode &) = delete; ObjectNode &operator=(const ObjectNode &) = delete; ~ObjectNode() { while (!m_children.empty()) { ObjectNode *child = m_children.back(); m_children.pop_back(); child->m_parent = nullptr; if (!child->m_heap) { ++m_faults; } else { delete child; } } if (m_parent) { auto &sibs = m_parent->m_children; sibs.erase(std::remove(sibs.begin(), sibs.end(), this), sibs.end()); } m_log.push_back(m_name); } void set_parent(ObjectNode *p) { if (m_parent == p || p == this) { return; } if (m_parent) { auto &old = m_parent->m_children; old.erase(std::remove(old.begin(), old.end(), this), old.end()); } m_parent = p; if (m_parent) { m_parent->m_children.push_back(this); } } private: std::string m_name; ObjectNode *m_parent = nullptr; bool m_heap; std::vector<ObjectNode *> m_children; std::vector<std::string> &m_log; int &m_faults; }; } // namespace hmi int main() { int closes = 0; { hmi::MoveHandle h1(9, &closes); hmi::MoveHandle h2(std::move(h1)); hmi::MoveHandle &alias = h2; h2 = std::move(alias); } assert(closes == 1); std::vector<std::string> log; int faults = 0; { auto root = std::make_unique<hmi::ObjectNode>("root", nullptr, true, log, faults); auto *early = new hmi::ObjectNode("early", root.get(), true, log, faults); new hmi::ObjectNode("label", root.get(), true, log, faults); new hmi::ObjectNode("btn", root.get(), true, log, faults); delete early; } assert(faults == 0); assert((log == std::vector<std::string>{"early", "btn", "label", "root"})); hmi::ObjectNode stack_child("stack_lbl", nullptr, false, log, faults); { hmi::ObjectNode shorter_parent("panel", nullptr, false, log, faults); stack_child.set_parent(&shorter_parent); } assert(faults == 1); std::printf("RAII closes=%d teardown=%s->%s->%s->%s stack_faults=%d\n", closes, log[0].c_str(), log[1].c_str(), log[2].c_str(), log[3].c_str(), faults); return 0; }- Guards self-move (this != &o) before calling reset() so moving an alias onto itself never closes a live handle.
- Detaches child->m_parent = nullptr before delete child; flags non-heap stack children instead of corrupting glibc heap.
Verifying Heap Teardown Order and Allocator System Calls
Check ./verify output: RAII closes=1 teardown=early->btn->label->root stack_faults=1. Explicitly deleting early logged its destruction immediately and detached it from root, leaving btn and label to be cleaned up in LIFO child order before root itself logged exit. Attaching stack_child to shorter_parent incremented stack_faults to 1 the instant shorter_parent's inner block exited.
Notice in strace how brk() establishes the C++ process heap arena once at startup, followed by all new/delete tree operations executing cleanly in user space without extra kernel syscalls before write(1, ...) and exit_group(0).
learner@ksa:~/gl-q01/m01-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m01-l02./verifyRAII closes=1 teardown=early->btn->label->root stack_faults=1learner@ksa:~/gl-q01/m01-l02learner@ksa:~/gl-q01/m01-l02strace -e trace=brk,write,exit_group ./verifybrk(NULL) = 0x6550aa822000brk(NULL) = 0x6550aa822000brk(0x6550aa843000) = 0x6550aa843000write(1, "RAII closes=1 teardown=early->bt"..., 62) = 62exit_group(0) = ?+++ exited with 0 +++Ownership Collisions in Production Qt 6 Codebases
Keep the ownership line razor-sharp in every code review: if an object inherits QObject and has a parent, allocate it with new and let the parent own it; if an object has no QObject parent—whether a root window or a Linux kernel device file descriptor—own it with a lexical stack scope, std::unique_ptr, or a Rule-of-Five guard.
Notice how Q_DISABLE_COPY_MOVE turns accidental value-copy bugs (void showPanel(QWidget w)) into immediate compile-time errors rather than silent object slicing. Next, Lesson 1.3 explores vptr/vtable polymorphism, operator overloads, and zero-overhead C++20 concept pipelines.
Calling delete this Directly Inside a Synchronous Slot Handler:
- Symptom: Clicking a 'Close Card'
QPushButtoninsideCardWidgettriggersdelete this;in the slot and crashes immediately insideQAbstractButton::mouseReleaseEventafter the slot returns. - Root Cause:
CardWidgetis the parent of theQPushButtoncurrently executing on the C++ call stack! Synchronousdelete thisdestroys the childQPushButtonwhileQPushButton's own member function is still active on the stack. - Fix: Call
this->deleteLater()instead ofdelete thisinside slots or event handlers so Qt posts aQEvent::DeferredDeleteticket processed safely after the active call stack unwinds.
Adding widget to a QLayout Without Realizing QLayout Reparents to the Host QWidget:
- Symptom: An engineer stores
std::unique_ptr<QPushButton> m_btn = std::make_unique<QPushButton>("Run");(initially parentless) and callslayout->addWidget(m_btn.get()), causing a double-free crash on window close. - Root Cause:
QLayout::addWidget()automatically callssetParent()to reparentm_btn.get()onto the layout's hostQWidget, silently creating dual ownership alongsidem_btn! - Fix: Allocate layout-managed widgets with
new QPushButton(tr("Run"), this)(or transfer ownership viam_btn.release()) and keep only a non-owningQPushButton *observer pointer.
Guided Practice
Modify verify.cpp to test the reverse stack declaration order: { ObjectNode parent("p", nullptr, false, log, faults); ObjectNode child("c", &parent, false, log, faults); }. Trace step-by-step why faults stays 0 in that exact block order (~child runs first and unlinks itself before ~parent runs), yet explain why coding guidelines still prefer heap allocation for child widgets when layouts reparent controls dynamically.
Independent Practice
Write a C++20 Rule-of-Five MmapRegion class wrapping a void * pointer and std::size_t byte length with std::exchange(other.m_addr, nullptr) move semantics, and embed it by value inside a Rule-of-Zero frame-buffer presenter class. Verify under -Wall -Wextra -Werror that copying the presenter is rejected at compile time while moving MmapRegion into its constructor compiles cleanly.
Verification Checks
? check 1 · What happens at the closing brace of { QLabel lbl; QWidget win; lbl.setParent(&win); } under standard C++20 stack unwinding?
- [x]
~QWidget()executes first in reverse declaration order and callsdelete &lblon stack memory. - [ ]
~QLabel()executes first becausesetParent(&win)reorders the compiler's stack-unwind table. - [ ]
setParent(&win)cloneslblonto the heap via copy construction and nulls out the stack local. - [ ]
~QWidget()inspects/proc/self/mapsand automatically skips freeing stack addresses.
Answer: ~QWidget() executes first in reverse declaration order and calls delete &lbl on stack memory.
Why: 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.
? check 2 · 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)?
- [ ]
std::unique_ptrcannot instantiate templates over classes that declareQ_OBJECT. - [ ]
QLabeldeclares its destructorprotected, causingstd::default_delete<QLabel>to fail. - [ ]
std::unique_ptrforces copy construction onQLabel, violatingQ_DISABLE_COPY_MOVE. - [x]
thisalready ownsm_statusviaQObjectparenting; wrapping it inunique_ptrcreates dual ownership.
Answer: this already owns m_status via QObject parenting; wrapping it in unique_ptr creates dual ownership.
Why: 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.
? check 3 · Inside FdGuard::operator=(FdGuard &&other), why must if (this != &other) guard reset()?
- [ ] Self-move assignment invokes
QObject::deleteChildren()recursively until the stack overflows. - [ ]
-Werror=pedanticrejects move-assignment operators that omit athis != &otherbranch. - [x] Without the self-check,
reset()closesm_fdbefore readingother.m_fd, destroying the active descriptor. - [ ] C++20
std::exchangethrowsstd::invalid_argumentwhenever source and destination addresses match.
Answer: Without the self-check, reset() closes m_fd before reading other.m_fd, destroying the active descriptor.
Why: 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.
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.
Step sequence — frame strip: steps_m01_l02
Wrap POSIX file descriptors or buffers in a Rule-of-Five guard that neutralizes moved-from state to -1.
reveals: step1
highlights: step1
Allocate child widgets via new with this as parent, keeping non-owning raw pointers as class members.
reveals: step2
highlights: step2
Verify that derived member destructors never delete a child that base ~QObject() also owns.
reveals: step3
highlights: step3
Keep parentless root QObjects on main()'s stack or inside std::unique_ptr for deterministic shutdown.
reveals: step4
highlights: step4
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.
Dynamic Widget Polymorphism Meets Zero-Overhead C++20 Static Constraints
Every QObject instance begins in memory with a hidden virtual table pointer (vptr: 8 bytes on LP64 x86_64, 4 bytes on ILP32 ARMv7-A) followed by QScopedPointer<QObjectData> d_ptr. That vptr makes heterogeneous UI trees possible: a QVBoxLayout holds QWidget * pointers and dispatches sizeHint(), event(QEvent *), and ~QWidget() dynamically through each subclass's vtable. Yet calling a virtual method inside a 20 kHz ADC sample loop forces an indirect call (call *[rax + offset]) on every sample and blocks loop vectorization.
Simultaneously, moc enforces a hard architectural rule: a Q_OBJECT class cannot be a class template (template <typename T> class Plot : public QWidget { Q_OBJECT }; fails moc compilation), because moc runs prior to C++ template instantiation and emits a single staticMetaObject table. C++20 resolves both tensions cleanly: model physical units as constexpr value types with operator<=>, run hot-loop math through C++20 concept function templates, and emit decimated updates from a final concrete QObject presenter!
Figure 1.3a. Keep arithmetic and filtering in constexpr value types and C++20 concepts; cross into /QObject dispatch only at frame cadence.
mental model: 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.
definition (vptr, vtable, and C++20 Concepts): 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.
- Step 1. Declare a public virtual destructor on every abstract base class deleted through a base pointer.
- Step 2. Mark derived virtual implementations with override and seal concrete leaf classes with final.
- Step 3. Give strongly typed scalar wrappers constexpr operator<=> and constrain DSP loops with C++20 concepts.
- Step 4. Place template <SampleFilter F> on a normal member function of a concrete Q_OBJECT presenter.
Figure 1.3b. Use virtual + override/final for runtime plugins/widgets, and C++20 concepts + <=> for hot data.
Inside Itanium C++ ABI Object Layout and Concept Instantiation
Inspect telemetry_sink.hpp below. MilliVolts wraps a std::int32_t with zero vptr, so sizeof(MilliVolts) == 4 and arrays pack contiguously in L1 cache. Defaulting constexpr auto operator<=>(const MilliVolts &) const noexcept = default; synthesizes all six relational operators (==, !=, <, <=, >, >=) in one line, while operator+ prevents accidentally adding raw MilliAmps to MilliVolts!
Next, look at how TelemetryPresenter works around moc's no-class-template rule: TelemetryPresenter itself is a concrete final QObject subclass, so moc happily generates its staticMetaObject and meanUpdated(std::int32_t) signal. Meanwhile, processBurst<F> is a regular C++20 SampleFilter-constrained member function template (NOT marked as a slot or signal), allowing g++ to inline the entire burst accumulation loop before emitting one change-guarded UI signal!
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.
| Polymorphism / Type Mechanism | Per-Object Memory Cost | Call Resolution & Inlining | Best Fit in Qt 6 HMIs |
|---|---|---|---|
virtual Base + override | +8 B vptr (x86_64) / +4 B (ARMv7-A) | Runtime vtable load; blocks cross-TU inlining | Heterogeneous QWidget trees, QAbstractItemModel, plugins |
virtual Leaf Marked final | +8 B / +4 B vptr (inherited) | Devirtualized direct call when static type is the final leaf | Concrete MainWindow, TelemetryPresenter, custom gauges |
C++20 concept Template | 0 B (sizeof holds payload only) | 100% compile-time bound; eligible for SIMD auto-vectorization | ADC ring-buffer filters, CRC framing, fixed-point DSP |
C++20 Value operator<=> / + | 0 B overhead over underlying scalar | constexpr inline register instructions | Strongly typed units (MilliVolts, MicroAmps, KiloPascals) |
learner@ksa:~/gl-q01/m01-l03$ bat -H 13 -H 35 telemetry_sink.hpp File: telemetry_sink.hpp #pragma once #include <QObject> #include <compare> #include <concepts> #include <cstdint> #include <span> namespace hmi { struct MilliVolts { std::int32_t mv = 0; constexpr auto operator<=>(const MilliVolts &) const noexcept = default; constexpr MilliVolts operator+(MilliVolts rhs) const noexcept { return MilliVolts{mv + rhs.mv}; } }; template <typename F> concept SampleFilter = requires(F filter, const F cfilter, MilliVolts sample) { { filter.push(sample) } noexcept -> std::same_as<void>; { cfilter.mean() } noexcept -> std::same_as<MilliVolts>; }; template <SampleFilter F> inline MilliVolts ingest_burst(F &filter, std::span<const MilliVolts> burst) noexcept { for (MilliVolts s : burst) { filter.push(s); } return filter.mean(); } class ITelemetryBackend { public: virtual ~ITelemetryBackend() = default; virtual MilliVolts readChannel(int ch) const noexcept = 0; }; class TelemetryPresenter final : public QObject { Q_OBJECT public: explicit TelemetryPresenter(QObject *parent = nullptr) : QObject(parent) {} template <SampleFilter F> void processBurst(F &filter, std::span<const MilliVolts> samples) { const MilliVolts avg = ingest_burst(filter, samples); if (avg != m_lastAvg) { m_lastAvg = avg; emit meanUpdated(avg.mv); } } signals: void meanUpdated(std::int32_t milliVolts); private: MilliVolts m_lastAvg{0}; }; } // namespace hmi- Defaulted C++20 operator<=> generates all 6 comparison operators with zero runtime overhead.
- virtual ~ITelemetryBackend() = default guarantees well-defined destruction via base unique_ptr.
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 Lesson 1.3 cpp20-polymorphism(7) GL-Q01 quick reference · full manual page: man 7 cpp20-polymorphism 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 constexpr + and <=> comparisons; (2) adding a virtual destructor grows PlainFilter by exactly sizeof(void *) bytes for the hidden vptr; (3) resetting a std::unique_ptr<ISink> runs both ~VirtualFilter() and ~ISink(); and (4) 31 CLOCK_MONOTONIC runs over 40,000 samples measure indirect ISink & dispatch versus SampleFilter concept dispatch.
Notice that correctness assertions check exact mathematical sums (50500 mV) and destructor counts (1/1) rather than fragile timing ratios, while volatile accumulation prevents dead-code elimination. Keep host x86_64 CLOCK_MONOTONIC numbers strictly scoped to host call overhead—never extrapolate them directly to ARMv7-A Cortex-A7 pipeline timing.
learner@ksa:~/gl-q01/m01-l03$ bat -H 15 -H 99 verify.cpp File: verify.cpp #include <algorithm> #include <array> #include <cassert> #include <compare> #include <concepts> #include <cstdint> #include <cstdio> #include <ctime> #include <memory> namespace hmi { struct MilliVolts { std::int32_t mv = 0; constexpr auto operator<=>(const MilliVolts &) const noexcept = default; constexpr MilliVolts operator+(MilliVolts r) const noexcept { return MilliVolts{mv + r.mv}; } }; struct PlainFilter { std::int64_t sum_mv = 0; std::int32_t count = 0; void push(MilliVolts s) noexcept { sum_mv += s.mv; ++count; } MilliVolts total() const noexcept { return MilliVolts{static_cast<std::int32_t>(sum_mv)}; } }; class ISink { public: explicit ISink(int *base_dtors) noexcept : m_base_dtors(base_dtors) {} virtual ~ISink() { if (m_base_dtors) { ++(*m_base_dtors); } } virtual void push(MilliVolts s) noexcept = 0; virtual MilliVolts total() const noexcept = 0; private: int *m_base_dtors; }; class VirtualFilter final : public ISink { public: VirtualFilter(int *base_dtors, int *derived_dtors) noexcept : ISink(base_dtors), m_derived_dtors(derived_dtors) {} ~VirtualFilter() override { if (m_derived_dtors) { ++(*m_derived_dtors); } } void push(MilliVolts s) noexcept override { m_sum += s.mv; } MilliVolts total() const noexcept override { return MilliVolts{static_cast<std::int32_t>(m_sum)}; } private: std::int64_t m_sum = 0; int *m_derived_dtors; }; template <typename F> concept SampleFilter = requires(F f, const F cf, MilliVolts s) { { f.push(s) } noexcept -> std::same_as<void>; { cf.total() } noexcept -> std::same_as<MilliVolts>; }; template <SampleFilter F> static void run_concept(F &f, int n) noexcept { for (int i = 1; i <= n; ++i) { f.push(MilliVolts{i * 10}); } } static void run_virtual(ISink &s, int n) noexcept { for (int i = 1; i <= n; ++i) { s.push(MilliVolts{i * 10}); } } static std::uint64_t mono_ns() noexcept { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } } // namespace hmi int main() { using hmi::MilliVolts; static_assert(sizeof(MilliVolts) == 4); static_assert((MilliVolts{1200} + MilliVolts{300}) == MilliVolts{1500}); static_assert(MilliVolts{900} < MilliVolts{1200}); struct Plain64 { std::int64_t x = 0; }; struct Poly64 { std::int64_t x = 0; virtual ~Poly64() = default; }; assert(sizeof(Poly64) == sizeof(Plain64) + sizeof(void *)); int base_dtors = 0, derived_dtors = 0; { std::unique_ptr<hmi::ISink> poly = std::make_unique<hmi::VirtualFilter>(&base_dtors, &derived_dtors); hmi::run_virtual(*poly, 100); assert(poly->total() == MilliVolts{50500}); } assert(derived_dtors == 1 && base_dtors == 1); constexpr int kRuns = 31; constexpr int kSamples = 40000; std::array<std::uint64_t, kRuns> virt_ns{}; std::array<std::uint64_t, kRuns> conc_ns{}; volatile std::int64_t guard = 0; for (int r = 0; r < kRuns; ++r) { hmi::VirtualFilter vf(nullptr, nullptr); hmi::ISink &iref = vf; const std::uint64_t t0 = hmi::mono_ns(); hmi::run_virtual(iref, kSamples); virt_ns[r] = hmi::mono_ns() - t0; guard += iref.total().mv; hmi::PlainFilter pf{}; const std::uint64_t t1 = hmi::mono_ns(); hmi::run_concept(pf, kSamples); conc_ns[r] = hmi::mono_ns() - t1; guard += pf.total().mv; } std::sort(virt_ns.begin(), virt_ns.end()); std::sort(conc_ns.begin(), conc_ns.end()); assert(guard != 0); std::printf("sizeof_mv=%zu vptr=+%zub dtors=%d/%d virt_p50=%lluns conc_p50=%lluns\n", sizeof(MilliVolts), sizeof(Poly64) - sizeof(Plain64), derived_dtors, base_dtors, static_cast<unsigned long long>(virt_ns[kRuns / 2]), static_cast<unsigned long long>(conc_ns[kRuns / 2])); return 0; }- Spaceship operator<=> and operator+ execute at compile time (verified by static_assert in main).
- Proves sizeof(Poly64) == sizeof(Plain64) + sizeof(void *) (+8B on LP64, +4B on ARMv7-A) and 1/1 polymorphic teardown.
Confirming vptr Size Growth and Polymorphic Teardown
Verify ./verify output: sizeof_mv=4 vptr=+8b dtors=1/1 on 64-bit Linux, followed by median virt_p50 and conc_p50 nanosecond measurements. static_assert proved MilliVolts relational and addition operators at compile time before main() even executed, and dtors=1/1 confirmed ~VirtualFilter() ran ahead of ~ISink() when std::unique_ptr<ISink> left scope.
Notice in strace that clock_gettime(CLOCK_MONOTONIC) resolves via the Linux kernel vDSO shared page without context-switching into Ring 0, leaving only write(1, ...) and exit_group(0) in the system-call trace.
learner@ksa:~/gl-q01/m01-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m01-l03./verifysizeof_mv=4 vptr=+8b dtors=1/1 virt_p50=85951ns conc_p50=85990nslearner@ksa:~/gl-q01/m01-l03learner@ksa:~/gl-q01/m01-l03strace -e trace=write,exit_group ./verifywrite(1, "sizeof_mv=4 vptr=+8b dtors=1/1 v"..., 66) = 66exit_group(0) = ?+++ exited with 0 +++Polymorphic Slicing, Overload Hiding, and moc Template Limits
Module 1 has established your C++20 and QObject architectural foundation: isolated target CMake autogen graphs, deterministic move guards paired with heap-parented QObject trees, and virtual/override/final UI boundaries fed by constexpr value types and C++20 concept pipelines.
Now put all three lessons into practice in the lab_m01_cpp20_qobject_raii engineering studio below, where you will diagnose and repair a broken C++20 FdHandle, ObjectNode::reparent(), and DeleteQueue deferred sweep library against a 5-check TAP version 13 harness.
Silent Virtual Hiding When Omitting the override Specifier:
- Symptom: Subclassing
QWidgetand writingvoid keyPressEvent(const QKeyEvent *e)(adding an extraconst!) 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; withoutoverride, C++ treatskeyPressEvent(const QKeyEvent *)as a brand-new unrelated overload rather than overriding thevtableslot! - Fix: Append
overrideto every virtual override in derived classes (void keyPressEvent(QKeyEvent *event) override;) so signature mismatches fail compilation immediately.
Placing Q_OBJECT Inside a C++ Class Template:
- Symptom: Writing
template <typename T> class SensorPlot : public QWidget { Q_OBJECT ... };fails during theAUTOMOCstep withError: Template classes not supported by Q_OBJECT. - Root Cause:
mocparses headers once before C++ template instantiation and cannot emit concretestaticMetaObjectsymbols for arbitrary future template argumentsT. - Fix: Factor signals, slots, and
Q_OBJECTinto 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 &)).
Guided Practice
Add a second SampleFilter-conforming struct ClampedFilter to verify.cpp that clamps each incoming MilliVolts sample into [MilliVolts{0}, MilliVolts{3300}] using <=> comparisons before accumulating, and verify run_concept(cf, 500) instantiates with zero changes to run_concept's template definition.
Independent Practice
Open labs/lab_m01_cpp20_qobject_raii/ and repair the three intentional ownership bugs in starter/core.cpp—self-move descriptor clobbering, ancestor-cycle reparent() corruption, and re-entrant DeleteQueue::flush() double deletion—until sh check.sh reports 5/5 TAP version 13 passes and ./files/lab_cli --bench records CLOCK_MONOTONIC percentiles.
Verification Checks
? check 1 · Why does moc reject template <typename SampleT> class WaveformView : public QWidget { Q_OBJECT ... };?
- [ ] ISO C++20 forbids class templates from inheriting from any base class with a
virtualdestructor. - [ ]
QWidgetis markedfinalin Qt 6.8, blocking template subclasses from overridingpaintEvent. - [ ]
CMAKE_AUTOUICreserves angle brackets<...>exclusively for.uiXML tag parsing. - [x]
mocgenerates concrete per-classQMetaObjectglobals prior to C++ template instantiation.
Answer: moc generates concrete per-class QMetaObject globals prior to C++ template instantiation.
Why: 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.
? check 2 · 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?
- [ ]
std::unique_ptr<ICanBus>slices*ptron construction unlessICanBusinheritsQObject. - [ ] Pure virtual functions automatically promote
~ICanBus()tovirtual, so no defect exists. - [x]
~ICanBus()is non-virtual, sodeletethroughICanBus *causes undefined behavior on derived buses. - [ ]
= defaultis rejected by-std=c++20whenever a class contains a pure virtual= 0method.
Answer: ~ICanBus() is non-virtual, so delete through ICanBus * causes undefined behavior on derived buses.
Why: 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.
? check 3 · What compile-time and optimization benefit comes from declaring class AlarmBanner final : public QWidget and marking bool event(QEvent *e) override?
- [ ]
finaldisablesQObjectparent-child destruction soAlarmBannercan be copied by value. - [x]
overridecatches base-signature mismatches at compile time, andfinallets calls viaAlarmBanner *devirtualize. - [ ]
finalstripsvptrandd_ptrfromAlarmBanner, shrinkingsizeof(AlarmBanner)to 1 byte. - [ ]
overrideregistersevent()insideQMetaObjectas a queued cross-thread signal automatically.
Answer: override catches base-signature mismatches at compile time, and final lets calls via AlarmBanner * devirtualize.
Why: 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.
1. Motivation
Production Qt 6 HMIs crash during dialog transitions when an RAII descriptor guard clobbers itself on self-move, dynamic widget reparenting introduces an ancestor cycle, or queuing deleteLater() on both a parent panel and its child button double-deletes the child on queue drain. In this studio you repair all three invariants in strict ISO C++20.
2. Learning objectives
- Preserve single-close descriptor ownership across move construction and self-move assignment in
hmi::FdHandle. - Enforce DAG acyclicity in
ObjectNode::reparent()by walkingis_ancestor_of(new_parent)before detaching the old parent. - Purge destroyed child pointers from
DeleteQueueinsideObjectNode::~ObjectNode()soflush()never double-deletes.
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7target runningLinux kernel6.12 LTS and Qt 6.8eglfsor Wayland HMI panel to observeQObject::destroyedandQEvent::DeferredDeleteordering on real modal dialogs.
5. Complete executable commands
learner@ksa:~/gl-q01/m01-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/m01-l03$ bat example.cpp File: example.cpp FdHandle &FdHandle::operator=(FdHandle &&other) noexcept { if (this != &other) { reset(); m_fd = std::exchange(other.m_fd, -1); m_closes = std::exchange(other.m_closes, nullptr); } return *this; } ... ObjectNode::~ObjectNode() { if (m_queue) { m_queue->cancel(this); // prevents double-free if child was also queued! } while (!m_children.empty()) { ... } }starter/core.cpp contains three realistic C++20/Qt ownership bugs: (1) FdHandle::operator= omits if (this != &other) and closes an aliased handle prematurely; (2) ObjectNode::reparent() checks new_parent == this without checking is_ancestor_of(new_parent), creating infinite destructor cycles; and (3) ObjectNode::~ObjectNode() forgets m_queue->cancel(this), causing DeleteQueue::flush() to delete an already-freed child.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/m01-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - enforces FdHandle self-move safety, early child unlink, and LIFO tree teardown ok 4 - moves subtrees via reparent() while rejecting self or descendant cycles ok 5 - cancels dying children from DeleteQueue during parent flush to prevent double-free # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-q01/m01-l03$ bat listing.txt File: listing.txt fd_closes=1 cycle_rejected=1 swept=1 destroyed=3Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
With all three fixes restored in files/core.cpp, make -B -C files archives libcore.a cleanly under g++ -std=c++20 -Wall -Wextra -Werror -pedantic -O2, and sh check.sh passes all 5/5 TAP version 13 assertions including AddressSanitizer-equivalent double-free and cycle checks.
9. Experiment variations
- Near transfer: Add a
find_child(std::string_view name)recursive lookup method toObjectNodematchingQObject::findChildpre-order traversal and add a unit test verifying lookup afterreparent(). - Far transfer: Implement a
WeakObjectPtr<ObjectNode>observer smart pointer (mirroring Qt'sQPointer<T>) backed by a shared control flag cleared inside~ObjectNode()so external caches detect deleted widgets inO(1).
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/m01-l03$ bat listing.txt File: listing.txt BENCH lab_m01_cpp20_qobject_raii clock=CLOCK_MONOTONIC benchmark_samples=40 warmup=5 p50_ns=328 p95_ns=357 p99_ns=363 sink=72000The CLOCK_MONOTONIC percentiles from ./files/lab_cli --bench measure host C++20 heap new/delete and vector unlink cost across a 3-node tree (p50 typically sub-microsecond). Never extrapolate host allocator latency to target ARMv7-A QWidget backing-store teardown or DRM framebuffer unmapping.
11. Troubleshooting
| Symptom | Root cause | Fix | ||
|---|---|---|---|---|
not ok 3 - enforces FdHandle self-move safety... | FdHandle::operator= calls reset() unconditionally when this == &other. | Wrap reset() and std::exchange assignments inside if (this != &other). | ||
not ok 4 - moves subtrees via reparent()... | reparent() permits attaching an ancestor underneath its own child or grandchild. | Return false immediately when `new_parent == this | is_ancestor_of(new_parent)`. | |
not ok 5 - cancels dying children from DeleteQueue... | DeleteQueue::flush() deletes panel (which deletes btn), then pops stale btn and deletes it again! | Call if (m_queue) m_queue->cancel(this); at the top of ObjectNode::~ObjectNode(). |
12. Guided questions
- Why does
ObjectNode::~ObjectNode()setchild->m_parent = nullptrBEFORE executingdelete childinside itswhile (!m_children.empty())loop?
- *Hint 1:* Trace what
child->detach_from_parent()would do inside~ObjectNode()ifchild->m_parentstill pointed to the dying parent. - *Hint 2:* If
child->m_parentremained non-null,delete childwould callstd::removeon the parent'sm_childrenvector while the parent is already popping that exact vector, wastingO(N^2)scans and risking iterator invalidation.
- Why must
ObjectNode::reparent()checkis_ancestor_of(new_parent)BEFORE callingdetach_from_parent()?
- *Hint 1:* What state is
this->parent()left in ifdetach_from_parent()runs first and the cycle check subsequently returnsfalse? - *Hint 2:* Detaching before validating
new_parentorphansthis(m_parent == nullptr) when a rejectedreparent()should be a strong no-op preserving the existing tree!
13. Independent challenges
Extend ObjectNode with a destroyed callback list (matching QObject::destroyed(QObject *)) that fires BEFORE base teardown completes, and verify that listeners observing a dying parent cannot see already-freed children in child_count().
14. Solutions and explanations
The reference files/core.cpp guards this != &other in FdHandle::operator=, validates new_parent == this || is_ancestor_of(new_parent) prior to mutating links in ObjectNode::reparent(), and cancels this from DeleteQueue at the start of ObjectNode::~ObjectNode().
Run locally in your terminal and check off each verification milestone.
Not started
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.
Step sequence — frame strip: steps_m01_l03
Declare a public virtual destructor on every abstract base class deleted through a base pointer.
reveals: step1
highlights: step1
Mark derived virtual implementations with override and seal concrete leaf classes with final.
reveals: step2
highlights: step2
Give strongly typed scalar wrappers constexpr operator<=> and constrain DSP loops with C++20 concepts.
reveals: step3
highlights: step3
Place template <SampleFilter F> on a normal member function of a concrete Q_OBJECT presenter.
reveals: step4
highlights: step4
m02/
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.
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.
Binary Compatibility and Zero-Copy Value Passing in Qt 6
On an embedded root filesystem, linking a background CAN-bus logger against Qt6::Widgets drags libQt6Widgets.so.6, libQt6Gui.so.6, HarfBuzz font shaping, FreeType, and platform display plugins into RAM. Qt 6 enforces a strict layered split: QtCore provides non-GUI primitives (QObject, event loops, containers, I/O); QtGui adds window surfaces, fonts, QPainter, and the Rendering Hardware Interface (QRhi); and two sibling UI layers branch above QtGui—QtWidgets for deterministic control panels and QtQuick for GPU scene graphs.
Across every module, Qt solves two classic C++ library pain points. First, adding a private member variable to an ordinary C++ header class changes sizeof(Class) and breaks every already-compiled binary (fragile base class ABI); Qt hides all fields behind a single opaque d_ptr paired with a q_ptr back-link. Second, Qt value types (QString, QByteArray, QImage) use atomic Copy-on-Write (COW) implicit sharing—fast when read via const APIs, yet prone to silent heap copies when non-const iterators touch shared buffers!
Figure 2.1a. d_ptr freezes sizeof(PublicClass) across Qt 6 minor releases while atomic QArrayData refcounts defer buffer cloning until mutation.
mental model: 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.
definition (PIMPL (d_ptr / q_ptr) and Implicit Sharing (COW)): 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.
- Step 1. Forward-declare ClassPrivate in the public header and keep only d_ptr inside the public class layout.
- Step 2. Store a back-pointer q_ptr inside ClassPrivate whenever private helpers must notify the public QObject.
- Step 3. Use QString for localized human text (UTF-16LE) and QByteArray or std::span<const uint8_t> for binary frames.
- Step 4. Force const iteration with std::as_const(), cbegin(), or constData() on non-const local container copies.
Figure 2.1b. d_ptr stabilizes ABI sizeof; std::as_const() and constData() prevent silent COW detaches.
Inside Qt 6 QArrayDataPointer Layout and UTF-16LE vs Byte Storage
Qt 6 modernized QString, QByteArray, and QList<T> around a three-word QArrayDataPointer header (24 bytes on 64-bit, 12 bytes on 32-bit ARMv7-A): d points to the heap QArrayData control block (atomic<int> ref_, flags, alloc capacity), ptr points directly to the first element (enabling zero-offset slicing and Small String / literal views via QStringLiteral with d == nullptr!), and size holds the element count.
Pay close attention to element encoding! QString stores 16-bit UTF-16LE char16_t (QChar) code units (2 * size payload bytes), because ICU, HarfBuzz, and platform text APIs operate on UTF-16, whereas QByteArray stores raw 8-bit char bytes (1 * size payload bytes). In cow_pimpl_codec.cpp below, FrameCodec hides its CRC table seed inside FrameCodecPrivate (with q_ptr back-link) and hashes a by-value QByteArray via std::as_const(frame) so begin() resolves to const char * without detaching!
Figure 2.1b. Qt 6's 3-word QArrayDataPointer decouples control-block ownership (d) from payload start (ptr), powering zero-alloc QStringLiteral.
| Qt 6 Type | Code Unit / Ownership | Pass-by-Read Idiom | Hidden Detach / Lifetime Trap |
|---|---|---|---|
QString | 16-bit UTF-16LE (char16_t), COW QArrayData | QStringView (non-owning) or const QString & | for (QChar c : nonConstStr) detaches when ref > 1 |
QStringLiteral("...") | Compile-time .rodata UTF-16LE (d == nullptr) | Initialize QString constants with 0 heap cost | Mutating s[0] allocates first heap buffer on demand |
QByteArray | 8-bit char + trailing '\0', COW QArrayData | QByteArrayView or std::span<const char> via constData() | Calling buf.data() or buf[i] on non-const buf detaches |
QStringView / QByteArrayView | Non-owning { const T *ptr, qsizetype n } | Pass by value (16 B in 2 CPU registers on LP64) | Dangles if temporary backing QString dies before use! |
learner@ksa:~/gl-q01/m02-l01$ bat -H 34 -H 54 cow_pimpl_codec.cpp File: cow_pimpl_codec.cpp #include <QByteArray> #include <QString> #include <QtGlobal> #include <cstdint> #include <memory> #include <utility> namespace hmi { class FrameCodecPrivate; class FrameCodec { public: explicit FrameCodec(std::uint32_t seed); ~FrameCodec(); FrameCodec(const FrameCodec &) = delete; FrameCodec &operator=(const FrameCodec &) = delete; std::uint32_t seedMask() const noexcept; std::uint32_t crcFast(QByteArray frame) const noexcept; static std::size_t utf16ByteWidth(QString label) noexcept; private: Q_DECLARE_PRIVATE(FrameCodec) std::unique_ptr<FrameCodecPrivate> d_ptr; }; class FrameCodecPrivate { public: FrameCodecPrivate(FrameCodec *q, std::uint32_t s) noexcept : q_ptr(q), seed(s) {} std::uint32_t mixWithPublicMask(std::uint8_t byte) const noexcept { Q_Q(const FrameCodec); return (q->seedMask() ^ seed) + byte; } FrameCodec *const q_ptr; std::uint32_t seed; std::uint64_t decodedFrames = 0; // Growing Private preserves sizeof(FrameCodec)! Q_DECLARE_PUBLIC(FrameCodec) }; FrameCodec::FrameCodec(std::uint32_t seed) : d_ptr(std::make_unique<FrameCodecPrivate>(this, seed)) {} FrameCodec::~FrameCodec() = default; std::uint32_t FrameCodec::seedMask() const noexcept { return 0x5A5A0000U; } std::uint32_t FrameCodec::crcFast(QByteArray frame) const noexcept { Q_D(const FrameCodec); std::uint32_t acc = d->mixWithPublicMask(0U); for (char byte : std::as_const(frame)) { // Zero detach even when ref > 1! acc = (acc * 33U) ^ static_cast<std::uint8_t>(byte); } return acc; } std::size_t FrameCodec::utf16ByteWidth(QString label) noexcept { const char16_t *units = reinterpret_cast<const char16_t *>(label.constData()); (void)units; return static_cast<std::size_t>(label.size()) * sizeof(char16_t); } } // namespace hmi- Q_Q(const FrameCodec) dereferences q_ptr so FrameCodecPrivate can query public FrameCodec methods cleanly.
- std::as_const(frame) forces cbegin()/cend() so iterating a shared QByteArray copy never triggers detach().
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 Lesson 2.1 QArrayData-PIMPL(3qt) GL-Q01 quick reference · full manual page: man 3qt QArrayData-PIMPL Proving d_ptr ABI Invariance and Range-For COW Hazards in C++20
In verify.cpp, we construct both a bidirectional d_ptr/q_ptr PimplPanel facade and a generic CowArray<T> container instantiated for char (ByteBuf) and char16_t (Utf16Str, matching QString UTF-16LE width). A global g_heap_allocs counter tracks every control-block allocation across value copies, range-for loops, and rvalue moves.
Look closely at lines 88-100 in verify.cpp: iterating ByteBuf bad_loop = master; via for (char c : bad_loop) invokes non-const begin(), sees use_count() == 2, and increments g_heap_allocs even though the loop never writes to c! Wrapping std::as_const(good_loop) calls begin() const and performs zero heap allocations.
learner@ksa:~/gl-q01/m02-l01$ bat -H 65 -H 95 verify.cpp File: verify.cpp #include <atomic> #include <cassert> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstring> #include <memory> #include <utility> static int g_heap_allocs = 0; template <typename T> class CowArray { struct Block { std::atomic<int> ref{1}; std::size_t len = 0; T data[1]; }; static Block *alloc_block(const T *src, std::size_t n) { ++g_heap_allocs; auto *raw = new char[sizeof(Block) + n * sizeof(T)]; auto *b = new (raw) Block{}; b->len = n; for (std::size_t i = 0; i < n; ++i) { b->data[i] = src[i]; } b->data[n] = T{}; return b; } static void release(Block *b) noexcept { if (b && b->ref.fetch_sub(1, std::memory_order_acq_rel) == 1) { b->~Block(); delete[] reinterpret_cast<char *>(b); } } public: CowArray(const T *s, std::size_t n) : m_b(alloc_block(s, n)) {} ~CowArray() { release(m_b); } CowArray(const CowArray &o) noexcept : m_b(o.m_b) { if (m_b) { m_b->ref.fetch_add(1, std::memory_order_relaxed); } } CowArray(CowArray &&o) noexcept : m_b(std::exchange(o.m_b, nullptr)) {} CowArray &operator=(const CowArray &) = delete; int use_count() const noexcept { return m_b ? m_b->ref.load(std::memory_order_relaxed) : 0; } std::size_t size() const noexcept { return m_b ? m_b->len : 0; } const T *const_data() const noexcept { return m_b->data; } void detach() { if (m_b && m_b->ref.load(std::memory_order_acquire) > 1) { Block *fresh = alloc_block(m_b->data, m_b->len); release(m_b); m_b = fresh; } } T *begin() { detach(); return m_b->data; } T *end() { detach(); return m_b->data + m_b->len; } const T *begin() const noexcept { return m_b->data; } const T *end() const noexcept { return m_b->data + m_b->len; } private: Block *m_b = nullptr; }; class PanelFacade { struct Private { PanelFacade *const q_ptr; std::uint32_t scale = 10U; std::uint64_t extra_abi_fields[4]{}; std::uint32_t compute(std::uint32_t v) const noexcept { return q_ptr->base_offset() + v * scale; } }; public: PanelFacade() : d_ptr(std::make_unique<Private>(Private{this, 10U, {}})) {} ~PanelFacade() = default; std::uint32_t base_offset() const noexcept { return 100U; } std::uint32_t eval(std::uint32_t v) const noexcept { return d_ptr->compute(v); } private: std::unique_ptr<Private> d_ptr; }; int main() { static_assert(sizeof(PanelFacade) == sizeof(void *)); PanelFacade panel; assert(panel.eval(7) == 170U); g_heap_allocs = 0; CowArray<char> master("CAN_ID_204", 10); assert(g_heap_allocs == 1 && master.use_count() == 1); CowArray<char> good_loop(master); unsigned sum_good = 0; for (char c : std::as_const(good_loop)) { sum_good += static_cast<unsigned char>(c); } assert(g_heap_allocs == 1 && master.use_count() == 2); CowArray<char> bad_loop(master); unsigned sum_bad = 0; for (char c : bad_loop) { // Non-const range-for triggers detach()! sum_bad += static_cast<unsigned char>(c); } assert(sum_good == sum_bad && g_heap_allocs == 2 && bad_loop.use_count() == 1); const char16_t u16_lit[] = u"RPM"; CowArray<char16_t> qstr(u16_lit, 3); assert(qstr.size() * sizeof(char16_t) == 6); std::printf("PIMPL sizeof=%zub q_eval=%u allocs_after_const=1 " "allocs_after_nonconst=%d utf16_bytes=%zu\n", sizeof(PanelFacade), panel.eval(7), g_heap_allocs, qstr.size() * sizeof(char16_t)); return 0; }- Non-const begin() must call detach(), whereas begin() const returns m_b->data directly with zero allocation.
- static_assert proves PanelFacade occupies one pointer (8B on LP64) despite Private holding 48+ bytes.
Verifying PIMPL Footprint and COW Allocation Counts
Inspect ./verify output: PIMPL sizeof=8b q_eval=170 allocs_after_const=1 allocs_after_nonconst=2 utf16_bytes=6. Even though PanelFacade::Private carries a 32-byte extra_abi_fields array, sizeof(PanelFacade) stays locked at 8 bytes (sizeof(void *)), and q_ptr resolved base_offset() + 7 * 10 == 170 cleanly.
Meanwhile, std::as_const(good_loop) kept g_heap_allocs at 1, whereas omitting std::as_const on bad_loop silently doubled heap allocations (2) for the exact same read-only checksum!
learner@ksa:~/gl-q01/m02-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m02-l01./verifyPIMPL sizeof=8b q_eval=170 allocs_after_const=1 allocs_after_nonconst=3 utf16_bytes=6learner@ksa:~/gl-q01/m02-l01learner@ksa:~/gl-q01/m02-l01strace -e trace=write,exit_group ./verifywrite(1, "PIMPL sizeof=8b q_eval=170 alloc"..., 86) = 86exit_group(0) = ?+++ exited with 0 +++Dangling Views, Incomplete-Type unique_ptr Destructors & False Detaches
Mastering d_ptr/q_ptr and implicit sharing explains why Qt 6 APIs pass QString and QByteArray cleanly across module boundaries without raw buffer ownership confusion—provided you pair read loops with std::as_const() / constData() and define PIMPL destructors out-of-line.
Next, Lesson 2.2 examines how Qt Designer .ui XML forms compile via uic into C++ setupUi() headers and why explicit PMF connect calls beat fragile connectSlotsByName naming conventions.
Inline Header Destructor on a Class Holding std::unique_ptr<FooPrivate>:
- Symptom: Writing
class Codec { ~Codec() {} ... std::unique_ptr<CodecPrivate> d_ptr; };incodec.hppfails compilation in client.cppfiles withinvalid application of 'sizeof' to incomplete type 'CodecPrivate'. - Root Cause:
std::default_delete<CodecPrivate>::operator()static-assertssizeof(CodecPrivate) > 0at the point where~Codec()is defined; incodec.hpp,CodecPrivateis only forward-declared! - Fix: Declare
~Codec();(without= defaultor{}) incodec.hpp, and placeCodec::~Codec() = default;insidecodec.cppbelow the full definition ofCodecPrivate.
Holding Raw constData() Pointers Across a Subsequent Non-Const Container Call:
- Symptom: Code obtains
const char *hdr = buf.constData();, then callsbuf[8] = 0x7E;whenbufwas shared (ref == 2), and later readshdr—observing stale or freed memory if the original owner also dropped its reference! - Root Cause:
buf[8] = 0x7Etriggersdetach(), allocating a brand-newQArrayDatabuffer forbufand decrementingrefon the blockhdrstill points into. - Fix: Re-acquire
constData()/ iterators AFTER all mutations finish, or calldetach()upfront before taking interior pointers.
Guided Practice
Add move-assignment and an edit_in_place(std::size_t idx, T val) method to CowArray<T> in verify.cpp, then pass std::move(bad_loop) into a sink function that mutates index 0. Confirm with assert(g_heap_allocs == 2) that mutating a moved buffer (use_count() == 1) modifies storage in place with zero heap allocations.
Independent Practice
Refactor a header-heavy sensor parser class into sensor_parser.hpp and sensor_parser.cpp using std::unique_ptr<SensorParserPrivate> d_ptr and SensorParser *const q_ptr. Add two new uint64_t counters to SensorParserPrivate and verify with nm / sizeof in a separate main.cpp that main.cpp.o's stack frame size for SensorParser never changes.
Verification Checks
? check 1 · 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?
- [x] Range-for on non-const
copycalls non-constcopy.begin(), which seesref == 2and runsdetach(). - [ ]
QStringcopy constructors alwaysmemcpyUTF-16LE buffers longer than 4 characters immediately. - [ ]
QChar::unicode()mutates surrogate-pair flags in place unlessQStringLiteralwas used. - [ ]
CMAKE_AUTOMOCinstruments range-for loops onQStringto emitQEvent::LanguageChange.
Answer: Range-for on non-const copy calls non-const copy.begin(), which sees ref == 2 and runs detach().
Why: 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.
? check 2 · How do d_ptr (Q_DECLARE_PRIVATE) and q_ptr (Q_DECLARE_PUBLIC) preserve binary compatibility across Qt 6 minor shared-library upgrades?
- [ ] Marking fields
private:inPublicClasshides them fromsizeof(PublicClass)under-std=c++20. - [ ]
q_ptrstores a dynamic JSON dictionary inQtCoreso member offsets are looked up by string name. - [ ]
d_ptrforces static linking oflibQt6Widgets.aso shared-library ABI rules never apply. - [x] Public classes store only
d_ptr, so adding fields inside*Privateleavessizeof(PublicClass)unchanged.
Answer: Public classes store only d_ptr, so adding fields inside *Private leaves sizeof(PublicClass) unchanged.
Why: 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.
? check 3 · Why must a headless Linux telemetry service link Qt6::Core instead of Qt6::Widgets in CMake?
- [ ]
Qt6::Coredisablesd_ptrallocations so allQObjectsubclasses fit on the stack. - [ ]
Qt6::Widgetscannot compile under-std=c++20withoutQt6::Quickalso linked. - [x]
Qt6::CoreprovidesQObject, event loops, and timers without pullingQt6::Gui, font, or display libraries. - [ ]
Qt6::WidgetsdeletesCLOCK_MONOTONICtimer support when no touchscreen is attached.
Answer: Qt6::Core provides QObject, event loops, and timers without pulling Qt6::Gui, font, or display libraries.
Why: 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.
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().
Step sequence — frame strip: steps_m02_l01
Forward-declare ClassPrivate in the public header and keep only d_ptr inside the public class layout.
reveals: step1
highlights: step1
Store a back-pointer q_ptr inside ClassPrivate whenever private helpers must notify the public QObject.
reveals: step2
highlights: step2
Use QString for localized human text (UTF-16LE) and QByteArray or std::span<const uint8_t> for binary frames.
reveals: step3
highlights: step3
Force const iteration with std::as_const(), cbegin(), or constData() on non-const local container copies.
reveals: step4
highlights: step4
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.
What Actually Happens to a Designer .ui File During Compilation
Engineers transitioning from web DOMs or QtQuick .qml scenes often assume a Qt Designer panel.ui XML file is parsed from /usr/share/ when a QWidget opens on target hardware. In standard QtWidgets builds (AUTOUIC ON), .ui XML never touches the embedded board! When panel.cpp writes #include "ui_panel.h", uic translates panel.ui at build time into a plain, non-QObject C++ class Ui_Panel (aliased as Ui::Panel) whose setupUi(QWidget *root) method executes ordinary new QVBoxLayout(root), new QPushButton(root), and setObjectName(...) calls.
At the very last line of setupUi(root), however, uic emits QMetaObject::connectSlotsByName(root). That legacy helper scans root's meta-object for slots named on_<objectName>_<signal>(...) at runtime! If an engineer writes void on_eStopBtn_clicked() and a designer later renames eStopBtn to haltDriveBtn inside Qt Designer, g++ -Wall -Wextra -Werror succeeds with zero warnings—and the emergency halt button silently does nothing on the shop floor!
Figure 2.2a. uic emits ordinary C++ widget allocations in ui_*.h, making explicit compile-time safe on widget renames.
mental model: 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.
definition (uic (User Interface Compiler) and Ui::Form Namespace): 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; }!
- Step 1. Forward-declare Ui::PumpPanel in pump_panel.hpp and hold std::unique_ptr<Ui::PumpPanel> m_ui privately.
- Step 2. Call m_ui->setupUi(this) inside the constructor body and define ~PumpPanel() = default in .cpp.
- Step 3. Connect every m_ui control with compile-time pointer-to-member QObject::connect calls.
- Step 4. Use code-first loops for N-channel telemetry grids while assigning stable objectName strings.
Figure 2.2b. Hold Ui::Form privately via unique_ptr, ban connectSlotsByName, and loop repetitive channels in C++.
Anatomy of Generated ui_*.h Code and Hybrid Form Composition
Notice a subtle ownership detail when PumpPanel holds std::unique_ptr<Ui::PumpPanel> m_ui in panel_uic_vs_code.cpp below! Does m_ui violate Lesson 1.2's rule against unique_ptr on child widgets? No—because Ui::PumpPanel is NOT a QWidget! Ui::PumpPanel is a plain C++ struct of raw observer pointers (sizeof = N * sizeof(void *)), while every new QPushButton(root) inside setupUi(this) passes this (PumpPanel *) as its QObject parent. Thus m_ui frees the 24-byte pointer struct, and ~QWidget() frees the actual child widgets!
Observe also how retranslateUi(this) works during live operator language switching (e.g., English to German on an exported machine): installing a new QTranslator posts QEvent::LanguageChange to top-level widgets, and overriding changeEvent(QEvent *e) to call m_ui->retranslateUi(this) updates every static label in place without destroying or recreating a single widget!
Figure 2.2b. Ui_PumpPanel is a non-QObject struct of observer pointers; the host QWidget passed to setupUi(this) owns every child control.
| UI Construction Approach | Git Diff & Review Clarity | Refactor / Rename Safety | Ideal Industrial Use Case |
|---|---|---|---|
Designer .ui + connectSlotsByName | Verbose XML diffs on minor coordinate nudges | Unsafe: renaming widget breaks on_name_sig at runtime | Avoid in production safety or mission-critical HMIs |
Designer .ui + Private m_ui + PMF connect | XML layout separated from .cpp controller logic | High: renaming widget breaks m_ui->widget at compile time | Fixed settings dialogs and static calibration forms |
Code-First C++ Loops (QHBoxLayout / QGridLayout) | Compact 5-20 line C++ diffs; trivial branch merges | Highest: 100% typed C++ identifiers and constexpr counts | Multi-channel telemetry strips, dynamic status matrices |
Runtime QUiLoader (.ui parsed on target) | Requires shipping XML + QtUiTools library | Lowest: all widget lookups via findChild strings | Rare user-customizable plugin forms only |
learner@ksa:~/gl-q01/m02-l02$ bat -H 16 -H 50 panel_uic_vs_code.cpp File: panel_uic_vs_code.cpp #include <QCoreApplication> #include <QEvent> #include <QHBoxLayout> #include <QLabel> #include <QPushButton> #include <QWidget> #include <array> #include <memory> // Exact structure emitted by uic into ui_pump_panel.h: class Ui_PumpPanel { public: QHBoxLayout *rootRow = nullptr; QPushButton *haltDriveBtn = nullptr; void setupUi(QWidget *PumpPanel) { PumpPanel->setObjectName(QStringLiteral("PumpPanel")); rootRow = new QHBoxLayout(PumpPanel); haltDriveBtn = new QPushButton(PumpPanel); haltDriveBtn->setObjectName(QStringLiteral("haltDriveBtn")); rootRow->addWidget(haltDriveBtn); retranslateUi(PumpPanel); } void retranslateUi(QWidget *) { haltDriveBtn->setText( QCoreApplication::translate("PumpPanel", "Halt Drive")); } }; namespace Ui { class PumpPanel : public Ui_PumpPanel {}; } class PumpPanelWidget final : public QWidget { Q_OBJECT public: static constexpr std::size_t kChannels = 4; explicit PumpPanelWidget(QWidget *parent = nullptr) : QWidget(parent), m_ui(std::make_unique<Ui::PumpPanel>()) { m_ui->setupUi(this); // Hybrid code-first loop for 4 identical channel badges: for (std::size_t i = 0; i < kChannels; ++i) { auto *cell = new QLabel(QStringLiteral("--.- kPa"), this); cell->setObjectName(QStringLiteral("ch_%1_kpa").arg(i)); m_ui->rootRow->insertWidget(static_cast<int>(i), cell); m_cells[i] = cell; } // Compile-time checked PMF connect (never on_haltDriveBtn_clicked!): connect(m_ui->haltDriveBtn, &QPushButton::clicked, this, &PumpPanelWidget::emergencyHaltRequested); } ~PumpPanelWidget() override = default; protected: void changeEvent(QEvent *ev) override { if (ev->type() == QEvent::LanguageChange) { m_ui->retranslateUi(this); } QWidget::changeEvent(ev); } signals: void emergencyHaltRequested(); private: std::unique_ptr<Ui::PumpPanel> m_ui; std::array<QLabel *, kChannels> m_cells{}; };- uic emits plain C++ heap allocations parented to PumpPanel and delegates text assignment to retranslateUi().
- Explicit PMF connect binds m_ui->haltDriveBtn to a signal-to-signal forwarder checked at compile time.
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> {}; } BEST PRACTICES 1. Hold std::unique_ptr<Ui::Form> privately; never inherit Ui::Form publicly. 2. Avoid on_<objectName>_<signal>() auto-connect slots; wire explicit PMFs. 3. Handle QEvent::LanguageChange in changeEvent() by calling retranslateUi(this). Kernel Systems Academy Lesson 2.2 uic(1) GL-Q01 quick reference · full manual page: man 1 uic Simulating uic setupUi(), Retranslation & Rename Hazards in C++20
In verify.cpp, we model Ui_PumpPanel::setup_ui() and retranslate_ui() in pure ISO C++20, populating a 4-channel hybrid control strip, testing recursive find_child() lookup by object_name, switching locale tables (en -> de) in place without reallocating widget nodes, and demonstrating connect_slots_by_name failure.
Watch what happens when eStopBtn is renamed to haltDriveBtn in the form descriptor: connect_slots_by_name drops from 1 matched slot to 0 silently at runtime while keeping exact compile-time validity, whereas direct member-pointer wiring fires reliably on click!
learner@ksa:~/gl-q01/m02-l02$ bat -H 30 -H 79 verify.cpp File: verify.cpp #include <array> #include <cassert> #include <cstdio> #include <memory> #include <string> #include <string_view> #include <vector> struct SimWidget { std::string class_name; std::string object_name; std::string text; std::vector<std::unique_ptr<SimWidget>> children; SimWidget *find_child(std::string_view target) noexcept { for (auto &ch : children) { if (ch->object_name == target) { return ch.get(); } if (SimWidget *sub = ch->find_child(target)) { return sub; } } return nullptr; } }; struct UiPumpPanel { SimWidget *halt_btn = nullptr; std::array<SimWidget *, 4> ch_labels{}; void setup_ui(SimWidget &host, std::string_view btn_obj_name) { host.object_name = "PumpPanel"; for (std::size_t i = 0; i < ch_labels.size(); ++i) { auto lbl = std::make_unique<SimWidget>(); lbl->class_name = "QLabel"; lbl->object_name = "ch_" + std::to_string(i) + "_kpa"; lbl->text = "--.- kPa"; ch_labels[i] = lbl.get(); host.children.push_back(std::move(lbl)); } auto btn = std::make_unique<SimWidget>(); btn->class_name = "QPushButton"; btn->object_name = std::string(btn_obj_name); halt_btn = btn.get(); host.children.push_back(std::move(btn)); retranslate_ui("en"); } void retranslate_ui(std::string_view locale) { halt_btn->text = (locale == "de") ? "Antrieb Stopp" : "Halt Drive"; } }; static int connect_slots_by_name(const SimWidget &host, const std::vector<std::string> &declared_slots) { int matches = 0; for (const auto &s : declared_slots) { for (const auto &ch : host.children) { if (s == "on_" + ch->object_name + "_clicked") { ++matches; } } } return matches; } int main() { SimWidget host_v1; auto ui_v1 = std::make_unique<UiPumpPanel>(); ui_v1->setup_ui(host_v1, "eStopBtn"); const std::vector<std::string> legacy_slots = {"on_eStopBtn_clicked"}; assert(connect_slots_by_name(host_v1, legacy_slots) == 1); // Designer renames eStopBtn -> haltDriveBtn; legacy slot name stays unchanged! SimWidget host_v2; auto ui_v2 = std::make_unique<UiPumpPanel>(); ui_v2->setup_ui(host_v2, "haltDriveBtn"); const int broken_auto_matches = connect_slots_by_name(host_v2, legacy_slots); assert(broken_auto_matches == 0); // Explicit member pointer & retranslate_ui keep exact identity across locales: SimWidget *before_ptr = ui_v2->halt_btn; ui_v2->retranslate_ui("de"); assert(ui_v2->halt_btn == before_ptr && ui_v2->halt_btn->text == "Antrieb Stopp"); assert(host_v2.find_child("ch_3_kpa") == ui_v2->ch_labels[3]); std::printf("uic children=%zu de_text='%s' auto_connect_after_rename=%d\n", host_v2.children.size(), ui_v2->halt_btn->text.c_str(), broken_auto_matches); return 0; }- setup_ui() builds 4 parameterized channel QLabel nodes plus the action button under host.children.
- Renaming eStopBtn to haltDriveBtn drops connect_slots_by_name matches to 0 without any compile error.
Confirming Zero-Realloc Retranslation and Auto-Connect Breakage
Confirm ./verify outputs uic children=5 de_text='Antrieb Stopp' auto_connect_after_rename=0. Switching locale from "en" to "de" updated halt_btn->text in place while ui_v2->halt_btn == before_ptr confirmed zero widget reallocation, and find_child("ch_3_kpa") resolved the fourth channel badge cleanly.
Equally clear, auto_connect_after_rename=0 proves why on_<objectName>_<signal> is banned in industrial code reviews: direct m_ui->haltDriveBtn member access turns any Designer rename into an instant C++ compile failure.
learner@ksa:~/gl-q01/m02-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m02-l02./verifyuic children=5 de_text='Antrieb Stopp' auto_connect_after_rename=0learner@ksa:~/gl-q01/m02-l02learner@ksa:~/gl-q01/m02-l02strace -e trace=write,exit_group ./verifywrite(1, "uic children=5 de_text='Antrieb "..., 67) = 67exit_group(0) = ?+++ exited with 0 +++Designer Form Inheritance, Missing LanguageChange & Layout Pitfalls
You now see .ui files for what they truly are: an optional ahead-of-time C++ widget-tree macro lowered by uic into ui_*.h with zero target XML runtime. Compose Ui::Form privately when static dialogs benefit from visual layout, build repetitive multi-channel instrumentation in clean C++ loops, and wire every signal explicitly.
Next, Lesson 2.3 opens Qt's deepest black box: how moc compiles Q_OBJECT into packed string tables, relative method offsets, void *_a[] argument arrays, and qt_static_metacall.
Public Multiple Inheritance (class Panel : public QWidget, public Ui::Panel):
- Symptom: External controller code writes
panel->haltDriveBtn->setEnabled(false);directly, scattering internal widget state mutations across 15 unrelated.cppfiles. - Root Cause: Inheriting
public Ui::Panelexposes every generated raw child pointer inUi_Panelas part ofPanel's public C++ API, destroying encapsulation. - Fix: Store
std::unique_ptr<Ui::Panel> m_ui;(orUi::Panel m_ui;inside.cpp-only classes) underprivate:and expose semantic controller methods (setDriveArmed(bool)) and signals (emergencyHaltRequested()).
Placing Fixed Pixel setGeometry() Widgets Without a Root QLayout in Designer:
- Symptom: A
.uipanel looks aligned at800x480in Designer, then clips half its buttons at1024x600or1280x800DPI scaling on target hardware. - Root Cause: Dropping widgets onto a Designer canvas without applying a top-level
QVBoxLayout/QGridLayoutmakesuicemit hardcodedsetGeometry(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
uicemitsQLayout::addWidgetrules.
Guided Practice
Extend UiPumpPanel in verify.cpp to store per-channel engineering unit strings updated inside retranslate_ui() ("kPa" in SI mode versus "PSI" in Imperial mode) without losing the live numeric telemetry reading currently displayed on ch_0_kpa..ch_3_kpa.
Independent Practice
Write a pure C++20 code-first layout specification for an 8-channel ThermocoupleMatrixWidget (2 rows x 4 columns) assigning objectName values tc_r0_c0 through tc_r1_c3 and forwarding all 8 per-cell fault-acknowledge buttons into a single channelAcknowledged(int channelIndex) signal.
Verification Checks
? check 1 · Which runtime file from status_panel.ui must be installed onto the embedded ARMv7-A root filesystem when built via CMAKE_AUTOUIC?
- [ ]
status_panel.uiunder/etc/qt6/ui/, becausesetupUi()streams the XML DOM on firstshow(). - [ ]
ui_status_panel.hunder/usr/lib/qt6/, becauselibQt6Widgets.soJIT-parses generated headers. - [ ] A
.qrcresource entry wrappingstatus_panel.ui, becauseAUTOUICdelegates toQUiLoader. - [x] None;
uicloweredstatus_panel.uiinto C++ statements inui_status_panel.hcompiled into the ELF binary.
Answer: None; uic lowered status_panel.ui into C++ statements in ui_status_panel.h compiled into the ELF binary.
Why: 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.
? check 2 · 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)?
- [ ]
on_ackBtn_clicked()disablesQObjectparent-child teardown when the parent dialog closes. - [ ]
uicomitsconnectSlotsByNamewhenever-std=c++20andCXX_EXTENSIONS OFFare enabled. - [x] Renaming
ackBtnin Designer breaks C++ compilation onm_ui->ackBtn, whereasconnectSlotsByNamefails only at runtime. - [ ]
connectSlotsByNameallocates a detachedQThreadper button and exhausts virtual address space.
Answer: Renaming ackBtn in Designer breaks C++ compilation on m_ui->ackBtn, whereas connectSlotsByName fails only at runtime.
Why: 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.
? check 3 · 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?
- [ ]
QCoreApplication::exec()garbage-collects alluicwidgets when the last window hides. - [x]
PumpPanelWidget's base~QObject()destructor deleteshaltDriveBtn;m_uionly frees the plainUi::PumpPanelpointer struct. - [ ]
~Ui_PumpPanel()callsdelete haltDriveBtnbefore~PumpPanelWidget()runs. - [ ] The caller must write
delete m_ui->haltDriveBtn;manually inside~PumpPanelWidget().
Answer: PumpPanelWidget's base ~QObject() destructor deletes haltDriveBtn; m_ui only frees the plain Ui::PumpPanel pointer struct.
Why: 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.
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.
Step sequence — frame strip: steps_m02_l02
Forward-declare Ui::PumpPanel in pump_panel.hpp and hold std::unique_ptr<Ui::PumpPanel> m_ui privately.
reveals: step1
highlights: step1
Call m_ui->setupUi(this) inside the constructor body and define ~PumpPanel() = default in .cpp.
reveals: step2
highlights: step2
Connect every m_ui control with compile-time pointer-to-member QObject::connect calls.
reveals: step3
highlights: step3
Use code-first loops for N-channel telemetry grids while assigning stable objectName strings.
reveals: step4
highlights: step4
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.
Zero Compiler Magic: How Signals Become Ordinary C++ Function Calls
Newcomers to Qt often treat signals:, slots:, and emit like magical language extensions hidden inside a patched C++ compiler. Open <qtmetamacros.h> and the mystery vanishes in three lines: #define emit, #define slots, and #define signals public! When g++ compiles emit readingUpdated(kPa, faultMask);, the emit token disappears completely during preprocessing, leaving a plain C++ member function call this->readingUpdated(kPa, faultMask);.
Where does the body of PressureSensor::readingUpdated come from if you only wrote its prototype in pressure_meta.hpp? moc writes that C++ function body inside moc_pressure_meta.cpp! Alongside a read-only qt_meta_stringdata offset/length table in .rodata, moc emits the signal body—packing stack pointers into void *_a[] = { nullptr, ... } and calling QMetaObject::activate—plus qt_static_metacall, a direct switch (_id) jump table casting _a[1..N] back to typed C++ arguments.
Figure 2.3a. Same-thread DirectConnection signal emission allocates zero heap bytes: receivers read arguments directly off the sender's stack via void *_a[].
mental model: 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.
definition (, qt_meta_stringdata, and qt_static_metacall): 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.
- Step 1. Inspect how Q_OBJECT declares staticMetaObject, two virtual hooks, and one static dispatcher.
- Step 2. Read qt_meta_stringdata's {offset, size} pairs indexing one contiguous NUL-separated char array.
- Step 3. Trace the -generated signal body packing nullptr at _a[0] and operand addresses at _a[1..N].
- Step 4. Follow peeling off base method counts until qt_static_metacall hits the local case.
Figure 2.3b. Signals pack {nullptr, &arg1..&argN} into void *_a[] and dispatch via base-subtracted metacall IDs.
Dissecting moc_*.cpp Byte-for-Byte: String Tables, _a[] & Inheritance
Why did Qt introduce qt_static_metacall instead of making every single slot a C++ virtual function? Count the cost: an application with 300 widgets and 40 slots per widget would bloat every vtable by 40 pointers and pay dynamic relocation fixups at ELF load time! Instead, Q_OBJECT adds a fixed two-method virtual footprint (metaObject() and qt_metacall()), while qt_static_metacall compiles all signals, slots, and properties of a class into one compact static switch (_id) statement.
Examine pressure_meta.hpp below, which pairs a Qt 6.8 PressureSensor class with the exact annotated C++ code moc emits into moc_pressure_meta.cpp. Notice two critical invariants: first, in scaleReading (local ID 1), returning std::int32_t writes through *reinterpret_cast<std::int32_t *>(_a[0]) = _r ONLY after checking if (_a[0]); second, qt_meta_stringdata stores { byteOffset, byteLen } pairs in offsetsAndSizes so moc never calls strlen or malloc during startup!
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.
| Meta-Object Artifact | Generated Location & Storage | Runtime Cost | Role in Signal/Slot Dispatch |
|---|---|---|---|
#define signals public / #define emit | <qtmetamacros.h> preprocessor tokens | 0 ns (erased before C++ AST) | Exposes &Class::sig to PMF connect and turns emit into a call |
qt_meta_stringdata_<Class> | moc_*.cpp constexpr .rodata struct | 0 heap bytes; XIP/page-cache shared | Provides class, signal, and slot names for introspection |
void *_a[] stack vector | Inside moc-generated signal C++ body | Stack pointer stores only (DirectConnection) | Passes return storage (_a[0]) and operand addresses (_a[1..N]) |
qt_static_metacall | moc_*.cpp static private member function | Direct C++ switch (_id) jump | Unpacks _a[1..N] and invokes the concrete C++ slot/signal |
learner@ksa:~/gl-q01/m02-l03$ bat -H 16 -H 45 pressure_meta.hpp File: pressure_meta.hpp #pragma once #include <QObject> #include <cstdint> namespace hmi { class PressureSensor : public QObject { Q_OBJECT public: explicit PressureSensor(QObject *parent = nullptr) : QObject(parent) {} void ingestSample(std::int32_t kPa, std::uint32_t faultMask) { if (kPa != m_lastKpa || faultMask != m_lastMask) { m_lastKpa = kPa; m_lastMask = faultMask; emit readingUpdated(kPa, faultMask); } } public slots: std::int32_t scaleReading(std::int32_t kPa, std::int32_t factor) const noexcept { return (kPa - m_tareKpa) * factor; } signals: void readingUpdated(std::int32_t kPa, std::uint32_t faultMask); private: std::int32_t m_lastKpa = 0; std::int32_t m_tareKpa = 101; std::uint32_t m_lastMask = 0; }; } // namespace hmi /* * Annotated excerpt of moc_pressure_meta.cpp generated by Qt 6.8 moc: * * void hmi::PressureSensor::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { * auto *_t = static_cast<PressureSensor *>(_o); * if (_c == QMetaObject::InvokeMetaMethod) { * switch (_id) { * case 0: _t->readingUpdated((*reinterpret_cast<std::add_pointer_t<std::int32_t>>(_a[1])), * (*reinterpret_cast<std::add_pointer_t<std::uint32_t>>(_a[2]))); break; * case 1: { std::int32_t _r = _t->scaleReading((*reinterpret_cast<std::add_pointer_t<std::int32_t>>(_a[1])), * (*reinterpret_cast<std::add_pointer_t<std::int32_t>>(_a[2]))); * if (_a[0]) *reinterpret_cast<std::int32_t *>(_a[0]) = std::move(_r); } break; * default: ; * } * } * } * * void hmi::PressureSensor::readingUpdated(std::int32_t _t1, std::uint32_t _t2) { * void *_a[] = { nullptr, * const_cast<void *>(reinterpret_cast<const void *>(std::addressof(_t1))), * const_cast<void *>(reinterpret_cast<const void *>(std::addressof(_t2))) }; * QMetaObject::activate(this, &staticMetaObject, 0, _a); * } */- emit disappears in preprocessing; readingUpdated(kPa, faultMask) calls the moc-emitted C++ body below.
- Non-void slot case 1 guards if (_a[0]) before writing _r because void signal connections pass _a[0] == nullptr.
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 Derived::qt_metacall calls _id = Base::qt_metacall(_c, _id, _a). When _id >= 0, Base has subtracted its method count so Derived switches on local 0..count-1. Kernel Systems Academy Lesson 2.3 moc(1) GL-Q01 quick reference · full manual page: man 1 moc Constructing a Packed String-Table and void** Meta-Object Engine in C++20
In verify.cpp, we build a faithful C++20 miniature of moc's generated tables: a constexpr MetaStringData table indexing one contiguous character buffer via {offset, len} pairs, a two-level MetaBase -> DerivedSensor hierarchy implementing qt_metacall base-offset subtraction, and activate() routing void *_a[] argument packs.
Verify every step of main(): string_at(1) slices "readingUpdated" without heap allocation, emitting reading_updated(245, 0x04U) forwards stack pointers through _a[1] and _a[2] into rx, and invoking global method ID 2 (scale_reading) writes 3100 directly into ret through _a[0]!
learner@ksa:~/gl-q01/m02-l03$ bat -H 25 -H 127 verify.cpp File: verify.cpp #include <array> #include <cassert> #include <cstdint> #include <cstdio> #include <memory> #include <string_view> #include <vector> namespace hmi { struct OffsetLen { std::uint32_t offset; std::uint32_t len; }; template <std::size_t NStrings, std::size_t BufSize> struct PackedMetaStrings { std::array<OffsetLen, NStrings> index; char chars[BufSize]; constexpr std::string_view at(std::size_t i) const noexcept { return std::string_view(chars + index[i].offset, index[i].len); } }; static constexpr PackedMetaStrings<3, 44> kSensorStrings = { {{{0, 13}, {14, 14}, {29, 12}}}, "DerivedSensor\0readingUpdated\0scaleReading\0" }; class MetaBase; using StaticMetacallFn = void (*)(MetaBase *, int local_id, void **a); struct MetaObject { const MetaObject *super; int method_offset; int method_count; StaticMetacallFn static_metacall; }; struct Connection { int global_sig_id; MetaBase *receiver; int global_slot_id; }; class MetaBase { public: virtual ~MetaBase() = default; virtual int qt_metacall(int id, void **a) { if (id < 0) { return id; } if (id < 1) { if (id == 0) { ++reset_count; (void)a; } return -1; } return id - 1; } void connect_raw(int global_sig, MetaBase *rx, int global_slot) { m_conns.push_back({global_sig, rx, global_slot}); } static void activate(MetaBase *sender, const MetaObject *mo, int local_sig_id, void **a) { const int global_sig = mo->method_offset + local_sig_id; for (const auto &c : sender->m_conns) { if (c.global_sig_id == global_sig && c.receiver) { c.receiver->qt_metacall(c.global_slot_id, a); } } } int reset_count = 0; private: std::vector<Connection> m_conns; }; class DerivedSensor final : public MetaBase { public: static const MetaObject kMeta; int qt_metacall(int id, void **a) override { id = MetaBase::qt_metacall(id, a); if (id < 0) { return id; } if (id < kMeta.method_count) { qt_static_metacall(this, id, a); return -1; } return id - kMeta.method_count; } void reading_updated(std::int32_t kpa, std::uint32_t mask) { void *a[] = { nullptr, const_cast<void *>(reinterpret_cast<const void *>(std::addressof(kpa))), const_cast<void *>(reinterpret_cast<const void *>(std::addressof(mask))), }; MetaBase::activate(this, &kMeta, 0, a); } std::int32_t scale_reading(std::int32_t kpa, std::uint32_t mask) { last_kpa = kpa; last_mask = mask; return kpa * 10; } std::int32_t last_kpa = 0; std::uint32_t last_mask = 0; private: static void qt_static_metacall(MetaBase *o, int local_id, void **a) { auto *self = static_cast<DerivedSensor *>(o); switch (local_id) { case 0: self->reading_updated( *reinterpret_cast<const std::int32_t *>(a[1]), *reinterpret_cast<const std::uint32_t *>(a[2])); break; case 1: { const std::int32_t r = self->scale_reading( *reinterpret_cast<const std::int32_t *>(a[1]), *reinterpret_cast<const std::uint32_t *>(a[2])); if (a[0]) { *reinterpret_cast<std::int32_t *>(a[0]) = r; } break; } default: break; } } }; static const MetaObject kBaseMeta{nullptr, 0, 1, nullptr}; const MetaObject DerivedSensor::kMeta{&kBaseMeta, 1, 2, &DerivedSensor::qt_static_metacall}; } // namespace hmi int main() { static_assert(hmi::kSensorStrings.at(0) == "DerivedSensor"); static_assert(hmi::kSensorStrings.at(1) == "readingUpdated"); static_assert(hmi::kSensorStrings.at(2) == "scaleReading"); hmi::DerivedSensor tx; hmi::DerivedSensor rx; tx.connect_raw(1, &rx, 2); // global sig 1 -> global slot 2 (local case 1) tx.reading_updated(245, 0x04U); assert(rx.last_kpa == 245 && rx.last_mask == 0x04U); std::int32_t ret = 0; std::int32_t in_kpa = 310; std::uint32_t in_mask = 0U; void *call_args[] = {&ret, &in_kpa, &in_mask}; assert(rx.qt_metacall(2, call_args) == -1 && ret == 3100); void *empty_args[] = {nullptr}; assert(rx.qt_metacall(0, empty_args) == -1 && rx.reset_count == 1); std::printf("moc sig='%.*s' rx_kpa=%d mask=0x%x ret=%d base_reset=%d\n", static_cast<int>(hmi::kSensorStrings.at(1).size()), hmi::kSensorStrings.at(1).data(), rx.last_kpa, rx.last_mask, ret, rx.reset_count); return 0; }- PackedMetaStrings models Qt 6 qt_meta_stringdata in constexpr .rodata with zero startup heap allocations.
- qt_static_metacall checks if (a[0]) before writing return value r so void signal emissions with a[0]==nullptr never crash.
Verifying String Table Slicing and void** Metacall Return Values
Confirm ./verify prints moc sig='readingUpdated' rx_kpa=245 mask=0x4 ret=3100 base_reset=1. Notice that tx.reading_updated(245, 0x04U) invoked scale_reading with a[0] == nullptr (safely ignoring the return value), whereas direct rx.qt_metacall(2, call_args) passed &ret in a[0] and captured ret=3100!
Next time you inspect an embedded crash dump in gdb and see QMetaObject::activate -> qt_static_metacall between a button click and your slot, you can read _id and ((int*)_a[1])[0] directly off the register/stack frame!
learner@ksa:~/gl-q01/m02-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m02-l03./verifymoc sig='readingUpdated' rx_kpa=310 mask=0x0 ret=3100 base_reset=1learner@ksa:~/gl-q01/m02-l03learner@ksa:~/gl-q01/m02-l03strace -e trace=write,exit_group ./verifywrite(1, "moc sig='readingUpdated' rx_kpa="..., 67) = 67exit_group(0) = ?+++ exited with 0 +++Custom QMetaType Registration & Hand-Written Signal Pitfalls
Module 2 has demystified Qt 6's binary and compile-time machinery: d_ptr/q_ptr ABI insulation, atomic Copy-on-Write QArrayDataPointer discipline, uic .ui-to-C++ lowering, and moc qt_meta_stringdata plus qt_static_metacall void **_a activation.
Proceed to the lab_m02_moc_signal_dispatch studio below to repair a multi-slot MetaEndpoint router supporting packed string introspection, block_signals(bool) prior-state restoration, and re-entrant mid-dispatch slot disconnection.
Writing a Hand-Coded Function Body for a Method Declared Under signals:
- Symptom: Linker aborts with
multiple definition of 'hmi::PressureSensor::readingUpdated(int, unsigned int)'betweenpressure_meta.cpp.oandmocs_compilation.cpp.o. - Root Cause:
mocALWAYS emits the C++ function body for every prototype listed undersignals:; providing a second body in your.cppfile violates the C++ One Definition Rule (ODR). - Fix: Leave
signals:entries strictly as declarations in your.hppfile and letmocgenerate theirQMetaObject::activatebodies.
Passing Unregistered Custom Structs Across Cross-Thread QueuedConnection:
- Symptom: A signal carrying
const CanPayload &works on same-threadDirectConnection, then silently fails at runtime withQObject::connect: Cannot queue arguments of type 'CanPayload'when moved to a workerQThread. - Root Cause: Same-thread
DirectConnectiononly forwards&payloadin_a[1], whereasQueuedConnectionmust heap-cloneCanPayloadviaQMetaTypeafter the sender returns! - Fix: Ensure custom payload structs are default/copy-constructible value types and declare
Q_DECLARE_METATYPE(CanPayload)(plusqRegisterMetaType<CanPayload>()if matched by string name).
Guided Practice
Add a third inheritance level CalibratedSensor : public DerivedSensor to verify.cpp with method_offset = 3 and method_count = 1, and trace how calling qt_metacall(3, args) peels off 1 in MetaBase and 2 in DerivedSensor before hitting local case 0 in CalibratedSensor.
Independent Practice
Open labs/lab_m02_moc_signal_dispatch/ and repair all three defects in starter/core.cpp—off-by-one _a[0] argument indexing, broken block_signals() return state, and iterator corruption on mid-emission disconnect_id()—so sh check.sh passes 5/5 TAP version 13 checks.
Verification Checks
? check 1 · What does _a[0] hold inside the void *_a[] array passed to qt_static_metacall during QMetaObject::InvokeMetaMethod?
- [ ] Parameter 1's address, because C++ arrays are zero-indexed and signals cannot return values.
- [ ] A pointer to
qt_meta_stringdataused to verify the slot signature string at runtime. - [x] A pointer to the return-value storage, or
nullptrwhen invoking avoidmethod or signal. - [ ] The
thispointer of the senderQObject, followed by parameter 1 at_a[1].
Answer: A pointer to the return-value storage, or nullptr when invoking a void method or signal.
Why: 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].
? check 2 · What do emit and signals expand to when g++ preprocesses a Qt 6.8 header?
- [ ]
emitspawns a coroutine frame under-std=c++20, andsignalsexpands toconstexpr. - [x]
emitexpands to nothing, andsignalsexpands topublic. - [ ]
emitexpands toQMetaObject::activate, andsignalsexpands toprotected virtual. - [ ]
emitwrites to an internaleventfdsyscall, andsignalsexpands toprivate.
Answer: emit expands to nothing, and signals expands to public.
Why: #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:.
? check 3 · Why does Derived::qt_metacall start with _id = Base::qt_metacall(_c, _id, _a);?
- [x] So
Baseeither handles its own method IDs (returning< 0) or subtracts its method count to yieldDerived's 0-based local index. - [ ] So
Basecan detachd_ptrcopy-on-write buffers beforeDerivedmutates member fields. - [ ] So
Baselocks a recursive mutex across everyDirectConnectionslot call. - [ ] So
BasereparentsDerivedontoQCoreApplication::instance()on first emission.
Answer: So Base either handles its own method IDs (returning < 0) or subtracts its method count to yield Derived's 0-based local index.
Why: 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.
1. Motivation
Debugging subtle Qt 6 signal bugs—nested QSignalBlocker scopes prematurely unblocking an editor, custom qt_metacall bridges miscalculating base method offsets, or one-shot slots disconnecting themselves mid-emission—requires mechanical mastery of moc dispatch. In this studio you repair a zero-allocation PackedStringTable and MetaEndpoint void ** router.
2. Learning objectives
- Resolve packed
.rodatastring slices and subtractm_offsetaccurately inMetaEndpoint::qt_metacallandactivate. - Return the prior boolean state from
MetaEndpoint::block_signals(bool)so nested signal blockers restore state without leaks. - Preserve iteration safety when a connected slot calls
disconnect_id()on its own connection duringactivate().
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7target runningLinux kernel6.12 LTS and Qt 6.8 to inspect.rodataqt_meta_stringdatasymbols viaarm-linux-gnueabihf-objdump -s -j .rodataand traceqt_static_metacallingdbserver.
5. Complete executable commands
learner@ksa:~/gl-q01/m02-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/m02-l03$ bat example.cpp File: example.cpp bool MetaEndpoint::block_signals(bool block) noexcept { const bool previous = m_blocked; m_blocked = block; return previous; // Essential for nested QSignalBlocker scopes! } int MetaEndpoint::qt_metacall(int global_id, void **args) { ... const int local_id = global_id - m_offset; if (local_id < m_count) { if (m_fn) m_fn(this, local_id, args); return -1; } return local_id - m_count; }starter/core.cpp contains three meta-object bugs: (1) qt_metacall() forgets to subtract m_offset from global_id; (2) block_signals(bool) returns the newly assigned m_blocked flag instead of the previous state, breaking nested blocker restoration; and (3) activate() omits m_offset when computing global_sig.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/m02-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - slices PackedStringTable without heap copies and subtracts m_offset in qt_metacall ok 4 - returns previous blocked state from block_signals(bool) and suppresses emissions ok 5 - delivers multi-slot void** packs safely across re-entrant mid-dispatch self-disconnect # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-q01/m02-l03$ bat listing.txt File: listing.txt str_idx=1 rx_acc=427 scaled_ret=60Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
Restoring base-offset arithmetic and prior-state preservation in files/core.cpp allows sh check.sh to compile libcore.a cleanly under -std=c++20 -Wall -Wextra -Werror -pedantic and pass all 5/5 TAP version 13 verification checks.
9. Experiment variations
- Near transfer: Write a 12-line RAII
SignalBlockerclass wrappingMetaEndpoint &that callsm_prev = ep.block_signals(true)in its constructor andep.block_signals(m_prev)in its destructor, proving nested scopes work automatically. - Far transfer: Extend
MetaEndpoint::connect_towith abool unique_connectionflag modelingQt::UniqueConnectionthat rejects duplicate(global_signal_id, receiver, global_slot_id)tuples.
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/m02-l03$ bat listing.txt File: listing.txt BENCH lab_m02_moc_signal_dispatch clock=CLOCK_MONOTONIC benchmark_samples=40 warmup=5 p50_ns=55 p95_ns=56 p99_ns=68 sink=112365000The CLOCK_MONOTONIC --bench percentiles measure two synchronous void ** metacall dispatches plus one packed string lookup per iteration in host RAM (p50 tens of nanoseconds). Never extrapolate host DirectConnection speed to cross-thread QueuedConnection heap marshaling or target ARMv7-A eventfd kernel wakeups.
11. Troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
not ok 3 - slices PackedStringTable... | qt_metacall or activate omitted m_offset conversion between global and local IDs. | Compute local_id = global_id - m_offset in qt_metacall and global_sig = m_offset + local_signal_id in activate. |
not ok 4 - returns previous blocked state... | block_signals(true) returned true on the first call instead of the prior false value. | Capture const bool previous = m_blocked; before overwriting m_blocked = block; and return previous;. |
not ok 5 - delivers multi-slot void** packs... | activate() failed to match global_sig or invalidated m_links while iterating. | Add m_offset + local_signal_id and iterate over the snapshot ID vector before erasing inactive links. |
12. Guided questions
- Why does
MetaEndpoint::activate()snapshot matching connection IDs before invokinglnk.receiver->qt_metacall(...)instead of ranging directly overm_links?
- *Hint 1:* What happens to
std::vector<Link>::iteratorif a slot invoked insideqt_metacallcallssender->connect_to(...)and triggers a vector reallocation? - *Hint 2:* Calling
connect_toinside an active slot can reallocatem_links's backing buffer, immediately invalidating raw iterators or references intom_links!
- Why does Qt's
QObject::blockSignals(bool)return the PREVIOUS boolean state rather thanvoid?
- *Hint 1:* Imagine function
outer()blocks signals, calls helperinner()which also temporarily blocks and unblocks signals, and thenouter()continues. - *Hint 2:* If
inner()unconditionally calledblockSignals(false)on exit instead ofblockSignals(previous), it would prematurely re-enable signals whileouter()still expects them blocked!
13. Independent challenges
Add a QueuedEnvelope ring queue to MetaEndpoint that deep-copies two int32_t arguments out of void **args when a connection is marked queued = true, and drains queued metacalls later after the sender's stack frame has returned.
14. Solutions and explanations
The reference files/core.cpp computes local_id = global_id - m_offset in qt_metacall(), global_sig = m_offset + local_signal_id in activate(), and preserves const bool previous = m_blocked in block_signals().
Run locally in your terminal and check off each verification milestone.
Not started
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.
Step sequence — frame strip: steps_m02_l03
Inspect how Q_OBJECT declares staticMetaObject, two virtual hooks, and one static dispatcher.
reveals: step1
highlights: step1
Read qt_meta_stringdata's {offset, size} pairs indexing one contiguous NUL-separated char array.
reveals: step2
highlights: step2
Trace the moc-generated signal body packing nullptr at _a[0] and operand addresses at _a[1..N].
reveals: step3
highlights: step3
Follow qt_metacall peeling off base method counts until qt_static_metacall hits the local case.
reveals: step4
highlights: step4
m03/
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.
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.
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 checking to runtime, turning typos into silent console warnings. Qt 6's pointer-to-member-function (PMF) syntax (connect(src, &Bus::fault, dst, &Panel::showFault)) verifies types at compile time and even lets a zero-argument slot like QWidget::update attach to a two-argument signal.
Yet C++20 lambdas introduced a subtle, devastating trap: the 3-argument overload connect(bus, &Bus::fault, [this] (int code) { m_label->setNum(code); });! Because no receiver QObject * was passed as a third argument, Qt attaches the lambda's lifetime ONLY to bus—AND executes the lambda on bus's thread! Close and delete your modal DiagnosticDialog while bus stays alive, emit one more fault, and the lambda dereferences freed this->m_label memory! Passing this as the 3rd context argument (connect(bus, &Bus::fault, this, [this]...)) cures both bugs in four characters.
Figure 3.1a. Every lambda capturing widget state MUST pass a context QObject* as the 3rd argument to QObject::connect.
mental model: 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>.
definition (Context QObject, Qt::AutoConnection, and Qt::UniqueConnection): 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.
- Step 1. Use 4-argument directly whenever a member slot matches or accepts a prefix of signal args.
- Step 2. Wrap overloaded Qt methods such as QWidget::update or QSpinBox::valueChanged in qOverload<Args...>().
- Step 3. Always pass 'this' (or the captured widget) as the 3rd context argument before any capturing lambda.
- Step 4. Pass Qt::UniqueConnection on idempotent PMF binds, or store ::Connection for lambdas.
Figure 3.1b. Always pass a 3rd-arg context QObject* for lambdas; use Qt::UniqueConnection on PMFs.
Inside QSlotObjectBase, Prefix Arity Dropping & UniqueConnection
How does Qt 6 invoke a C++20 lambda or member pointer without moc knowing the lambda's signature? Instead of routing through qt_static_metacall, template QObject::connect allocates a tiny polymorphic QtPrivate::QFunctorSlotObject (or QCallableObject) node holding a static function pointer (impl) and the closure by value. During QMetaObject::activate, Qt passes void **_a straight into that QSlotObjectBase node, which unpacks only the prefix 0..K arguments the callable expects!
Now understand why Qt::UniqueConnection works on &DiagnosticPopup::refreshBadge in pmf_lifetime_panel.cpp below, yet CANNOT deduplicate two calls to connect(..., [this]{ ... })! Under the ISO C++20 standard, every lambda expression has a unique anonymous closure type, and even calling the same helper function twice creates two distinct QFunctorSlotObject instances without comparable member-function addresses. Use PMFs when you need Qt::UniqueConnection, or hold a QMetaObject::Connection member and disconnect prior to reconnecting!
Figure 3.1b. Dual-linked Connection nodes let either ~Sender() or ~Context() sever a slot in O(1) list manipulation.
| QObject::connect Form | Compile-Time Type Check | Receiver Delete Safety | Worker -> GUI Thread Safe | |
|---|---|---|---|---|
Legacy SIGNAL() / SLOT() macros | None (checked at runtime only) | Yes (dst is a QObject *) | Yes (dst->thread() known) | |
3-arg connect(src, &S::sig, [this]{...}) | Yes (C++20 template traits) | NO — dangles after ~this()! | NO — runs on src worker thread! | |
4-arg connect(src, &S::sig, this, [this]{...}) | Yes (prefix args allowed) | Yes (severed in ~QObject()) | Yes (queues onto this->thread()) | |
4-arg PMF + Qt::UniqueConnection | Yes (exact + implicit conversions) | Yes + rejects duplicate binds | Yes (`AutoConnection | UniqueConnection`) |
learner@ksa:~/gl-q01/m03-l01$ bat -H 29 -H 35 pmf_lifetime_panel.cpp File: pmf_lifetime_panel.cpp #include <QLabel> #include <QMetaObject> #include <QObject> #include <QString> #include <QWidget> namespace hmi { class TelemetryBus : public QObject { Q_OBJECT public: explicit TelemetryBus(QObject *parent = nullptr) : QObject(parent) {} signals: void faultRaised(int code, const QString &subsystem); void tareCaptured(int milliVolts); }; class DiagnosticPopup final : public QWidget { Q_OBJECT public: DiagnosticPopup(TelemetryBus *bus, QWidget *parent = nullptr) : QWidget(parent), m_badge(new QLabel(this)) { bindBus(bus); bindBus(bus); // Idempotent: UniqueConnection prevents double PMF bind! } void bindBus(TelemetryBus *bus) { // 1. PMF + UniqueConnection + prefix arity (2-arg signal -> 0-arg update) connect(bus, &TelemetryBus::faultRaised, this, qOverload<>(&QWidget::update), static_cast<Qt::ConnectionType>(Qt::AutoConnection | Qt::UniqueConnection)); // 2. 4-arg context-bound lambda (disconnects old handle before re-binding) QObject::disconnect(m_faultConn); m_faultConn = connect( bus, &TelemetryBus::faultRaised, this, [this] (int code, const QString &sub) { m_badge->setText(QStringLiteral("[%1] %2").arg(code).arg(sub)); }); // 3. One-shot calibration capture auto-severed on first fire OR ~Popup() QObject::disconnect(m_tareConn); m_tareConn = connect( bus, &TelemetryBus::tareCaptured, this, [this] (int mv) { m_tareMv = mv; QObject::disconnect(m_tareConn); }); } private: QLabel *m_badge = nullptr; QMetaObject::Connection m_faultConn; QMetaObject::Connection m_tareConn; int m_tareMv = 0; }; } // namespace hmi- qOverload<>(&QWidget::update) selects 0-arg update() and Qt::UniqueConnection deduplicates repeated bindBus() calls.
- Passing 'this' as the 3rd context argument prevents use-after-free when DiagnosticPopup closes while TelemetryBus lives on.
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 QMetaObject::Connection and call QObject::disconnect(handle). Kernel Systems Academy Lesson 3.1 QObject-connect(3qt) GL-Q01 quick reference · full manual page: man 3qt QObject-connect Verifying Context Auto-Prune, UniqueConnection & 3-Arg Hazards in C++20
In verify.cpp, we implement a C++20 Signal<Args...> dispatcher tracking ContextObject std::weak_ptr<bool> lifetime tokens, PMF (receiver, slot_tag) UniqueConnection deduplication, one-shot disconnect(conn_id) handles, and the 3-argument contextless hazard.
Follow the assertions in main(): calling connect_pmf twice with unique = true registers only one slot (popup.hits == 2 across two emissions, not 4), destroying popup auto-prunes both its PMF and 4-arg lambda slots on the next emission, whereas connect_3arg_hazard fires into dead scope (dangling_fires == 1)!
learner@ksa:~/gl-q01/m03-l01$ bat -H 27 -H 73 verify.cpp File: verify.cpp #include <algorithm> #include <cassert> #include <cstdio> #include <functional> #include <memory> #include <vector> namespace hmi { class ContextObject { public: ContextObject() : m_alive(std::make_shared<bool>(true)) {} virtual ~ContextObject() { *m_alive = false; } ContextObject(const ContextObject &) = delete; ContextObject &operator=(const ContextObject &) = delete; std::weak_ptr<bool> token() const noexcept { return m_alive; } private: std::shared_ptr<bool> m_alive; }; template <typename... Args> class Signal { public: template <typename Recv> int connect_pmf(Recv *rx, void (Recv::*pmf)(Args...), int pmf_tag, bool unique_conn = false) { if (unique_conn) { for (const auto &s : m_slots) { if (s.active && s.rx_ptr == rx && s.pmf_tag == pmf_tag) { return 0; // Qt::UniqueConnection rejected duplicate! } } } const int id = m_next_id++; m_slots.push_back({id, rx, pmf_tag, true, rx->token(), true, [rx, pmf] (Args... a) { (rx->*pmf)(a...); }}); return id; } template <typename Fn> int connect_4arg(const ContextObject *ctx, Fn &&fn) { const int id = m_next_id++; m_slots.push_back({id, ctx, -1, true, ctx->token(), true, std::function<void(Args...)>(std::forward<Fn>(fn))}); return id; } template <typename Fn> int connect_3arg_hazard(Fn &&fn) { const int id = m_next_id++; m_slots.push_back({id, nullptr, -1, false, {}, true, std::function<void(Args...)>(std::forward<Fn>(fn))}); return id; } bool disconnect(int id) noexcept { for (auto &s : m_slots) { if (s.id == id && s.active) { s.active = false; return true; } } return false; } void emit_sig(Args... args) { const std::size_t n = m_slots.size(); for (std::size_t i = 0; i < n; ++i) { if (!m_slots[i].active) { continue; } if (m_slots[i].has_ctx) { auto sp = m_slots[i].life.lock(); if (!sp || !*sp) { m_slots[i].active = false; continue; } } m_slots[i].fn(args...); } m_slots.erase( std::remove_if(m_slots.begin(), m_slots.end(), [] (const Entry &e) { return !e.active; }), m_slots.end()); } std::size_t active_count() const noexcept { return m_slots.size(); } private: struct Entry { int id; const ContextObject *rx_ptr; int pmf_tag; bool has_ctx; std::weak_ptr<bool> life; bool active; std::function<void(Args...)> fn; }; int m_next_id = 1; std::vector<Entry> m_slots; }; class Popup final : public ContextObject { public: void on_fault(int code) { sum += code; ++hits; } int sum = 0; int hits = 0; }; } // namespace hmi int main() { hmi::Signal<int> fault_sig; int safe_ctx_sum = 0; int one_shot_count = 0; { hmi::Popup dlg; assert(fault_sig.connect_pmf(&dlg, &hmi::Popup::on_fault, 1, true) > 0); assert(fault_sig.connect_pmf(&dlg, &hmi::Popup::on_fault, 1, true) == 0); fault_sig.connect_4arg(&dlg, [&] (int c) { safe_ctx_sum += c; }); int once_id = 0; once_id = fault_sig.connect_4arg(&dlg, [&] (int) { ++one_shot_count; fault_sig.disconnect(once_id); }); fault_sig.emit_sig(10); fault_sig.emit_sig(25); assert(dlg.hits == 2 && dlg.sum == 35); assert(safe_ctx_sum == 35 && one_shot_count == 1); } // dlg is now destroyed: 4-arg and PMF slots must auto-prune! fault_sig.emit_sig(100); assert(safe_ctx_sum == 35 && fault_sig.active_count() == 0); int dangling_fires = 0; { hmi::Popup transient; (void)transient; fault_sig.connect_3arg_hazard([&] (int) { ++dangling_fires; }); } fault_sig.emit_sig(404); assert(dangling_fires == 1); std::printf("PMF unique_dup=0 ctx_sum=%d one_shot=%d pruned=%zu uaf_3arg=%d\n", safe_ctx_sum, one_shot_count, fault_sig.active_count(), dangling_fires); return 0; }- unique_conn rejects duplicate (rx_ptr, pmf_tag) registration and returns null handle 0, matching Qt::UniqueConnection.
- Expired receiver life token marks the connection inactive instead of invoking a dangling [this] closure.
Confirming UniqueConnection Deduplication and Context Pruning
Verify ./verify prints PMF unique_dup=0 ctx_sum=35 one_shot=1 pruned=0 uaf_3arg=1. Passing unique_conn = true rejected the duplicate Popup::on_fault registration (0), destroying dlg kept ctx_sum frozen at 35 when 100 was emitted (pruned=0), and the 3-argument contextless lambda proved why omitting a context object fires into destroyed state (uaf_3arg=1).
Make this a zero-exception team lint rule: grep every connect( call in pull requests and require a 4th argument whenever the 3rd argument begins with [!
learner@ksa:~/gl-q01/m03-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m03-l01./verifyPMF unique_dup=0 ctx_sum=35 one_shot=1 pruned=1 uaf_3arg=1learner@ksa:~/gl-q01/m03-l01learner@ksa:~/gl-q01/m03-l01strace -e trace=write,exit_group ./verifywrite(1, "PMF unique_dup=0 ctx_sum=35 one_"..., 59) = 59exit_group(0) = ?+++ exited with 0 +++Qt::UniqueConnection on Lambdas & Multi-Pointer Capture Traps
With 4-argument context-bound QObject::connect and Qt::UniqueConnection in your toolkit, signal connections become both compile-time type-checked and teardown-safe.
Next, Lesson 3.2 traces what happens underneath queued connections and user input: how QCoreApplication::exec() drives the event loop, why postEvent and sendEvent have opposite memory-ownership rules, and how installEventFilter intercepts events in LIFO order.
Passing Qt::UniqueConnection to a Lambda QObject::connect Call:
- Symptom: In Qt 6, passing
Qt::UniqueConnectionto a lambdaconnect(src, &S::sig, this, [this]{...}, Qt::UniqueConnection)fails compilation (static_assertin 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 usingQt::UniqueConnection, or storeQMetaObject::Connectionand disconnect the prior handle before reconnecting.
Capturing [&] Reference-to-Stack-Locals Inside an Asynchronous Slot Lambda:
- Symptom: Writing
int threshold = 80; connect(timer, &QTimer::timeout, this, [&] { check(threshold); });inside a constructor crashes or reads garbage whentimeoutfires 50 ms later! - Root Cause: Constructor stack local
thresholddies as soon as the constructor returns, leaving[&]holding a dangling stack reference even thoughthisis 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.
Guided Practice
Extend Signal in verify.cpp to support prefix-argument binding (Signal<int, int>::connect_0arg(ctx, fn)), allowing a zero-argument callback [] { ... } to attach to a (int code, int severity) signal just like qOverload<>(&QWidget::update) in Qt 6.
Independent Practice
Audit a multi-dialog HMI workflow where a temporary CalibrationWizard connects to a singleton SensorManager AND references a sibling StatusFooter *footer. Show how to combine this as the 3rd connect context argument with QPointer<StatusFooter> safeFooter = footer; captured by value so destroying EITHER widget first is 100% memory-safe.
Verification Checks
? check 1 · 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?
- [ ] On
label's GUI thread, becauseg++inspects the lambda capture list[label]automatically. - [ ] On a newly spawned
QThreadPoolthread created perAutoConnectionemission. - [ ] Nowhere;
mocrefuses to emit signals from worker threads unlessQt::DirectConnectionis set. - [x] On the worker thread—causing undefined GUI race corruption—because no receiver context
QObject *was passed.
Answer: On the worker thread—causing undefined GUI race corruption—because no receiver context QObject * was passed.
Why: 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.
? check 2 · 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?
- [ ]
QWidget::updateis a variadic C function (...) that ignores stack arguments. - [ ] It only compiles when
CXX_EXTENSIONS ONenables GNU arity-truncation extensions. - [x] PMF
QObject::connecttraits allow a slot to accept any valid prefix (0..Kargs) of the signal's parameters. - [ ]
qOverload<>synthesizes two dummyintandQStringparameters ontoQWidget::update.
Answer: PMF QObject::connect traits allow a slot to accept any valid prefix (0..K args) of the signal's parameters.
Why: 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.
? check 3 · 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)?
- [ ] It deduplicates both PMF member slots and inline
[this] { ... }C++20 lambdas identically. - [x] If
(bus, &Bus::fault, this, &Panel::onFault)is already connected, Qt skips adding a duplicate and returns an invalid handle. - [ ] Qt disconnects ALL other receivers attached to
bussothisbecomes the sole listener. - [ ] Qt deletes
busand recreates itsQMetaObjecttable from scratch.
Answer: If (bus, &Bus::fault, this, &Panel::onFault) is already connected, Qt skips adding a duplicate and returns an invalid handle.
Why: 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.
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.
Step sequence — frame strip: steps_m03_l01
Use 4-argument PMF connect directly whenever a member slot matches or accepts a prefix of signal args.
reveals: step1
highlights: step1
Wrap overloaded Qt methods such as QWidget::update or QSpinBox::valueChanged in qOverload<Args...>().
reveals: step2
highlights: step2
Always pass 'this' (or the captured widget) as the 3rd context argument before any capturing lambda.
reveals: step3
highlights: step3
Pass Qt::UniqueConnection on idempotent PMF binds, or store QMetaObject::Connection for lambdas.
reveals: step4
highlights: step4
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.
Inside QCoreApplication::exec(): Multiplexing, Ownership & Interception
When main() enters app.exec(), Qt's thread-local QEventDispatcherUNIX (or Glib) sleeps inside ppoll() / epoll_wait() monitoring Wayland or evdev input descriptors, socket notifiers, an internal wake-up eventfd, and the next timer deadline—burning 0% CPU while idle. Events enter QCoreApplication::notify(receiver, event) down two very different roads: sendEvent invokes notify() synchronously right now on your current stack frame, whereas postEvent locks the receiver thread's mutex, appends the QEvent * to a priority queue, pokes eventfd, and deletes the event after delivery!
Before notify() ever calls receiver->event(ev), it walks every watcher attached via receiver->installEventFilter(watcher) in reverse installation order (LIFO). That single hook lets an industrial safety controller block axis-jogging keys across twenty spinboxes and buttons when an enclosure door opens—without subclassing a single widget!
Figure 3.2a. postEvent takes heap ownership and compresses repaints; sendEvent borrows stack events synchronously; LIFO filters consume on true.
mental model: 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.
definition (QCoreApplication::postEvent, sendEvent, and eventFilter): 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().
- Step 1. Use new QEvent exclusively for postEvent and stack QEvent variables for synchronous sendEvent.
- Step 2. Call QWidget::update() inside data slots so Qt coalesces multiple dirty regions into one QPaintEvent.
- Step 3. Remember LIFO ordering when stacking audit loggers and safety interlock filters on one widget.
- Step 4. End every eventFilter override with return BaseClass::eventFilter(watched, event) (false).
Figure 3.2b. Heap-allocate for postEvent, stack-allocate for sendEvent, and end eventFilter with false.
Priority Queue Ordering, Repaint Compression & LIFO Filter Mechanics
Look inside safety_event_filter.cpp below. JogInterlockFilter watches multiple motion controls on a CNC pendant. When m_guardClosed == false and a QEvent::KeyPress arrives for Qt::Key_Up or Qt::Key_Down, eventFilter emits motionBlocked for the status bar and returns true—halting propagation before ANY earlier-installed filter or watched->event() can move the spindle. For every other event (QEvent::Paint, QEvent::FocusIn, Qt::Key_Escape), QObject::eventFilter returns false so rendering and emergency cancel keys behave normally.
Examine schedulePanelRefresh and injectSyncSelfTest below the class as well. Why does QWidget::update() post QEvent::UpdateRequest at Qt::LowEventPriority (-1)? Because draining all NormalEventPriority (0) socket, timer, and input events FIRST lets fifty incoming telemetry updates mutate widget properties in nanoseconds before Qt executes one single expensive QPainter raster pass at the end of the turn!
Figure 3.2b. Scheduling UpdateRequest at LowEventPriority (-1) guarantees all pending data mutations settle before a single paintEvent runs.
| Dispatch / Redraw Call | Execution Timing | Event Allocation | Coalescing & Stack Safety |
|---|---|---|---|
QCoreApplication::sendEvent | Immediate synchronous call | Stack QKeyEvent ev(...); | Zero coalescing; re-enters immediately on current stack |
QCoreApplication::postEvent | Asynchronous on target loop turn | Heap new CustomEvent(...) | Thread-safe; queue deletes event after notify() |
QWidget::update() | Deferred LowEventPriority (-1) | Internal compressed UpdateRequest | 100 calls in one turn merge into 1 paintEvent |
QWidget::repaint() | Immediate synchronous raster pass | Direct stack QPaintEvent | Bypasses compression; stalls slot and risks recursion |
learner@ksa:~/gl-q01/m03-l02$ bat -H 22 -H 25 safety_event_filter.cpp File: safety_event_filter.cpp #include <QCoreApplication> #include <QEvent> #include <QKeyEvent> #include <QObject> #include <QWidget> namespace hmi { class JogInterlockFilter final : public QObject { Q_OBJECT public: explicit JogInterlockFilter(QObject *parent = nullptr) : QObject(parent) {} void setGuardClosed(bool closed) noexcept { m_guardClosed = closed; } protected: bool eventFilter(QObject *watched, QEvent *event) override { if (!m_guardClosed && event->type() == QEvent::KeyPress) { const auto *ke = static_cast<const QKeyEvent *>(event); if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down) { emit motionBlocked(watched, ke->key()); return true; // Consumed: watched->event() never executes! } } return QObject::eventFilter(watched, event); // Returns false: forward! } signals: void motionBlocked(QObject *control, int qtKey); private: bool m_guardClosed = false; }; inline void postDeferredRefresh(QObject *panel) { // Heap-allocated: postEvent takes ownership and deletes after dispatch QCoreApplication::postEvent( panel, new QEvent(QEvent::UpdateRequest), Qt::LowEventPriority); } inline bool sendSyncEscapeKey(QWidget *dialog) { // Stack-allocated: sendEvent borrows &esc synchronously without deleting QKeyEvent esc(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); return QCoreApplication::sendEvent(dialog, &esc); } } // namespace hmi- Returning true aborts event delivery immediately so neither earlier filters nor watched->keyPressEvent() run.
- Delegating unhandled events to QObject::eventFilter returns false so QEvent::Paint and Focus events reach watched.
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 Lesson 3.2 QCoreApplication-events(3qt) GL-Q01 quick reference · full manual page: man 3qt QCoreApplication-events Verifying Priority Draining, Paint Compression & LIFO Filters in C++20
In verify.cpp, we build a deterministic C++20 EventDispatcher modeling priority-sorted post_event(std::unique_ptr<Ev>) ownership, per-widget UpdateRequest compression, synchronous stack send_event(Ev &), and LIFO install_event_filter chains.
Inspect main(): audit is installed first and door is installed second (LIFO). While door.closed == false, sending Key_Up (100) hits door first, increments door.blocked, and returns true before audit or jog_btn ever sees the key! Posting 6 UpdateRequest events alongside a high-priority key drains KeyPress first and coalesces all 6 updates into 1 paint pass.
learner@ksa:~/gl-q01/m03-l02$ bat -H 60 -H 70 verify.cpp File: verify.cpp #include <algorithm> #include <cassert> #include <cstdio> #include <memory> #include <vector> namespace hmi { enum class EvType { KeyPress, UpdateRequest }; struct Ev { EvType type; int key = 0; }; class SimWidget { public: virtual ~SimWidget() = default; void install_event_filter(SimWidget *watcher) { if (watcher && watcher != this) { m_filters.erase( std::remove(m_filters.begin(), m_filters.end(), watcher), m_filters.end()); m_filters.push_back(watcher); } } virtual bool event_filter(SimWidget *, Ev *) { return false; } virtual bool event(Ev *e) { if (e->type == EvType::KeyPress) { ++key_hits; last_key = e->key; order_log.push_back(1); return true; } if (e->type == EvType::UpdateRequest) { ++paint_passes; order_log.push_back(2); return true; } return false; } const std::vector<SimWidget *> &filters() const noexcept { return m_filters; } int key_hits = 0; int paint_passes = 0; int last_key = 0; std::vector<int> order_log; private: std::vector<SimWidget *> m_filters; }; class EventDispatcher { public: static bool send_event(SimWidget *dst, Ev *e) { const auto &flts = dst->filters(); for (auto it = flts.rbegin(); it != flts.rend(); ++it) { if ((*it)->event_filter(dst, e)) { return true; } } return dst->event(e); } void post_event(SimWidget *dst, std::unique_ptr<Ev> e, int prio) { if (e->type == EvType::UpdateRequest) { for (const auto &q : m_queue) { if (q.dst == dst && q.ev->type == EvType::UpdateRequest) { return; // Coalesce duplicate pending UpdateRequest! } } } m_queue.push_back({prio, m_seq++, dst, std::move(e)}); } std::size_t drain() { std::sort(m_queue.begin(), m_queue.end(), [] (const Queued &a, const Queued &b) { return (a.prio != b.prio) ? (a.prio > b.prio) : (a.seq < b.seq); }); std::size_t dispatched = 0; while (!m_queue.empty()) { Queued cur = std::move(m_queue.front()); m_queue.erase(m_queue.begin()); send_event(cur.dst, cur.ev.get()); ++dispatched; } return dispatched; } private: struct Queued { int prio; std::size_t seq; SimWidget *dst; std::unique_ptr<Ev> ev; }; std::size_t m_seq = 0; std::vector<Queued> m_queue; }; struct AuditFilter final : public SimWidget { int seen = 0; bool event_filter(SimWidget *, Ev *) override { ++seen; return false; } }; struct DoorFilter final : public SimWidget { bool closed = false; int blocked = 0; bool event_filter(SimWidget *, Ev *e) override { if (!closed && e->type == EvType::KeyPress && e->key == 100) { ++blocked; return true; } return false; } }; } // namespace hmi int main() { hmi::EventDispatcher loop; hmi::SimWidget jog_btn; hmi::AuditFilter audit; hmi::DoorFilter door; jog_btn.install_event_filter(&audit); jog_btn.install_event_filter(&door); // Installed 2nd -> runs 1st (LIFO)! hmi::Ev stack_up{hmi::EvType::KeyPress, 100}; hmi::EventDispatcher::send_event(&jog_btn, &stack_up); assert(door.blocked == 1 && audit.seen == 0 && jog_btn.key_hits == 0); door.closed = true; hmi::EventDispatcher::send_event(&jog_btn, &stack_up); assert(door.blocked == 1 && audit.seen == 1 && jog_btn.key_hits == 1); jog_btn.order_log.clear(); for (int i = 0; i < 6; ++i) { loop.post_event(&jog_btn, std::make_unique<hmi::Ev>(hmi::Ev{hmi::EvType::UpdateRequest, 0}), -1); } loop.post_event(&jog_btn, std::make_unique<hmi::Ev>(hmi::Ev{hmi::EvType::KeyPress, 27}), +1); const std::size_t drained = loop.drain(); assert(drained == 2 && jog_btn.paint_passes == 1 && jog_btn.last_key == 27); assert((jog_btn.order_log == std::vector<int>{1, 2})); std::printf("Events blocked=%d audit=%d keys=%d paints=%d drained=%zu\n", door.blocked, audit.seen, jog_btn.key_hits, jog_btn.paint_passes, drained); return 0; }- Reverse iterator (flts.rbegin()..rend()) enforces Qt's LIFO eventFilter execution order.
- Duplicate UpdateRequest events targeting the same widget coalesce in the posted queue before drain().
Confirming LIFO Interception and Repaint Coalescing
Verify ./verify prints Events blocked=1 audit=1 keys=2 paints=1 drained=2. Installing door after audit caused door to intercept the unsafe keystroke before audit could even log it (audit=0 on the blocked pass, 1 after closing the guard), and order_log == {1, 2} proved that priority +1 (KeyPress) executed ahead of coalesced priority -1 (UpdateRequest).
Notice how encoding post_event's parameter as std::unique_ptr<Ev> in C++20 makes passing a stack address impossible at compile time!
learner@ksa:~/gl-q01/m03-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m03-l02./verifyEvents blocked=1 audit=3 keys=2 paints=1 drained=2learner@ksa:~/gl-q01/m03-l02learner@ksa:~/gl-q01/m03-l02strace -e trace=write,exit_group ./verifywrite(1, "Events blocked=1 audit=3 keys=2 "..., 51) = 51exit_group(0) = ?+++ exited with 0 +++Blank Widgets From Bad Filters & Nested processEvents() Re-Entrancy
You now control every stage of QEvent delivery: stack sendEvent versus heap postEvent, LowEventPriority repaint compression via update(), and centralized LIFO eventFilter interlocks.
Next, Lesson 3.3 completes Module 3 by connecting the event loop to hardware time: CLOCK_MONOTONIC timer heaps, Qt::PreciseTimer versus Qt::CoarseTimer's 5% coalescing window, and why long synchronous slots starve QPaintEvent frames.
Returning true by Accident at the Bottom of eventFilter():
- Symptom: After installing a custom
eventFilteron aQLineEditorQPushButton, the widget turns completely blank and ignores mouse clicks and focus. - Root Cause: Returning
trueon the default path tellsQCoreApplication::notifythat EVERY event—includingQEvent::Paint,QEvent::Resize, andQEvent::MouseButtonPress—was consumed! - Fix: Return
trueONLY inside the narrowif (...)branch that intentionally blocks an event, and always end withreturn QObject::eventFilter(watched, event);(false).
Sprinkling QCoreApplication::processEvents() Inside Long Slot Loops:
- 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 orDeferredDeleteevents to re-enter slots or destroythisbefore 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 a0 ms/ periodicQTimer).
Guided Practice
Modify install_event_filter in verify.cpp to verify what happens when the SAME filter &audit is installed a second time after &door: confirm that Qt removes the earlier &audit entry and appends &audit at the back, promoting &audit to run FIRST in LIFO order!
Independent Practice
Design an inactivity screen-dimmer IdleTouchFilter installed once on QApplication::instance() (global application event filter!) that observes QEvent::MouseButtonPress, QEvent::TouchBegin, and QEvent::KeyPress across every widget in the application to reset a backlight timer while always returning false.
Verification Checks
? check 1 · What happens if an engineer writes QEvent ev(QEvent::User); QCoreApplication::postEvent(panel, &ev);?
- [ ]
postEventblocks synchronously untilpanel->event(&ev)returns so&evstays valid. - [ ]
g++ -std=c++20rejects taking the address of a stackQEventlocal at compile time. - [x]
postEventqueues stack address&evand later executesdelete &ev, corrupting the C++ heap. - [ ]
postEventdetects automatic storage and copy-constructsevonto the heap safely.
Answer: postEvent queues stack address &ev and later executes delete &ev, corrupting the C++ heap.
Why: 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.
? check 2 · Filter Logger is installed first via btn->installEventFilter(logger), followed by btn->installEventFilter(interlock). When interlock->eventFilter returns true, what executes?
- [ ]
btn->eventruns first, andinterlockcancels the default aftermath. - [x]
interlockruns first and consumes the event; neitherlogger->eventFilternorbtn->eventruns. - [ ]
loggerruns first in FIFO order, theninterlockblocksbtn->event. - [ ] Both
interlockandloggeralways run, andtrueonly suppressesbtn->eventafterward.
Answer: interlock runs first and consumes the event; neither logger->eventFilter nor btn->event runs.
Why: 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.
? check 3 · Why should a 500 Hz telemetry slot call gauge->update() rather than gauge->repaint()?
- [x]
update()posts a low-priorityUpdateRequestthat Qt compresses into oneQPaintEventper frame. - [ ]
repaint()drops all pending mouse clicks in theLinux kernelevdevring buffer. - [ ]
update()rasterizesQPainterpaths automatically on a backgroundQThreadPoolworker. - [ ]
repaint()is deprecated and no-ops under Wayland andeglfsplatform plugins.
Answer: update() posts a low-priority UpdateRequest that Qt compresses into one QPaintEvent per frame.
Why: 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.
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.
Step sequence — frame strip: steps_m03_l02
Use new QEvent exclusively for postEvent and stack QEvent variables for synchronous sendEvent.
reveals: step1
highlights: step1
Call QWidget::update() inside data slots so Qt coalesces multiple dirty regions into one QPaintEvent.
reveals: step2
highlights: step2
Remember LIFO ordering when stacking audit loggers and safety interlock filters on one widget.
reveals: step3
highlights: step3
End every eventFilter override with return BaseClass::eventFilter(watched, event) (false).
reveals: step4
highlights: step4
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.
Wall-Clock Jumps, 5% Timer Jitter & Cooperative Frame Starvation
Embedded Linux panels frequently boot with 1970-01-01 RTC time before chronyd steps CLOCK_REALTIME forward by decades—or an operator adjusts shift time backward by five minutes. Any timeout computed from QDateTime::currentMSecsSinceEpoch() either fires early or freezes for five minutes! Both QTimer and QElapsedTimer anchor exclusively to the Linux kernel's CLOCK_MONOTONIC, which ticks strictly upward from boot.
Even on CLOCK_MONOTONIC, three behaviors catch engineers off guard. First, QTimer defaults to Qt::CoarseTimer, shifting deadlines by up to 5% (+/-2.5 ms on a 50 ms timer) to group CPU wakeups; tight 20 ms HMI scopes need Qt::PreciseTimer. Second, QTimer is NOT a preemptive POSIX signal or hardware interrupt! It is an entry in the thread's QTimerInfoList min-heap: if a synchronous slot blocks the GUI thread for 100 ms, neither QTimer nor QPaintEvent (WM_PAINT / UpdateRequest) can run until that slot returns!
Figure 3.3a. GUI-thread QTimers and QPaintEvents share one cooperative thread: blocking any slot freezes both timers and screen repaints.
mental model: 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.
definition (QTimerInfoList, Qt::TimerType, and QElapsedTimer): 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).
- Step 1. Call setTimerType() before start() whenever +/-5% coarse jitter is unacceptable.
- Step 2. Pass 'this' as the 2nd argument to QTimer::singleShot so widget destruction cancels delayed slots.
- Step 3. Anchor periodic deadlines to the initial monotonic phase and skip past missed intervals after stalls.
- Step 4. Measure slot duration and inter-tick delta with QElapsedTimer to surface hidden main-thread stalls.
Figure 3.3b. Use CLOCK_MONOTONIC phase grids, PreciseTimer for cadence, and <8 ms GUI slots so Paint runs.
How Blocking Slots Starve Both QTimerInfoList and QPaintEvent
Trace one turn of QApplication::exec() on a 60 Hz (16.67 ms period) industrial touchscreen: (1) epoll_wait wakes at t = 20.0 ms because a Qt::PreciseTimer expired; (2) QTimerInfoList::activateTimers() emits timeout(), invoking your slot; (3) your slot calls gauge->update(), queueing a LowEventPriority UpdateRequest; and (4) ONLY AFTER your slot returns does Qt drain UpdateRequest to issue QPaintEvent (or WM_PAINT on Windows / surface commit on Wayland)!
If step (2) performs a synchronous 90 ms serial retry or unindexed SQLite scan, step (4) cannot execute for 90 ms—dropping five consecutive 60 Hz frames—and the 20 ms timer misses ticks at 40, 60, and 80 ms! In monotonic_frame_watchdog.cpp below, FrameWatchdog monitors BOTH slotUs (catching our own slow slot) AND interTickUs (catching any OTHER slow slot on the GUI thread that delayed our wakeup), while binding QTimer::singleShot safely to this.
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.
| Timing Primitive / API | Underlying Clock / Mode | Behavior Across NTP / Stalls | Recommended HMI Role |
|---|---|---|---|
QDateTime::currentMSecsSinceEpoch | CLOCK_REALTIME (wall clock) | Jumps backward/forward on NTP sync! | Human audit timestamps ONLY; never timeouts |
QElapsedTimer::nsecsElapsed() | CLOCK_MONOTONIC (8 B value) | Strictly non-decreasing; zero heap cost | Slot latency budgets, retry deadlines, FPS math |
QTimer (Qt::CoarseTimer, default) | CLOCK_MONOTONIC + 5% batching | Shifts up to 5%; skips missed stall ticks | Status blinks, tooltips, non-critical UI polls |
QTimer (Qt::PreciseTimer) | CLOCK_MONOTONIC exact deadline | Phase-locked; still blocked by slow GUI slots | 20-60 Hz waveform strip charts & watchdogs |
learner@ksa:~/gl-q01/m03-l03$ bat -H 16 -H 25 monotonic_frame_watchdog.cpp File: monotonic_frame_watchdog.cpp #include <QElapsedTimer> #include <QObject> #include <QTimer> #include <cstdint> namespace hmi { class FrameWatchdog final : public QObject { Q_OBJECT public: static constexpr int kPeriodMs = 20; static constexpr std::int64_t kSlotBudgetUs = 8000; // 8 ms (< 16.67 ms 60 Hz) explicit FrameWatchdog(QObject *parent = nullptr) : QObject(parent), m_timer(new QTimer(this)) { m_timer->setTimerType(Qt::PreciseTimer); m_timer->setInterval(kPeriodMs); connect(m_timer, &QTimer::timeout, this, &FrameWatchdog::onTick); } void startWithWarmupBanner() { m_interTick.start(); m_timer->start(); // Context-bound singleShot: auto-cancels if FrameWatchdog dies < 250 ms! QTimer::singleShot(250, this, &FrameWatchdog::warmupFinished); } signals: void pollTelemetry(); void warmupFinished(); void frameStallDetected(std::int64_t slotUs, std::int64_t interTickUs); private slots: void onTick() { const std::int64_t interUs = m_interTick.nsecsElapsed() / 1000; m_interTick.restart(); QElapsedTimer slotClock; slotClock.start(); emit pollTelemetry(); const std::int64_t slotUs = slotClock.nsecsElapsed() / 1000; if (slotUs > kSlotBudgetUs || interUs > (kPeriodMs * 1500LL)) { emit frameStallDetected(slotUs, interUs); } } private: QTimer *m_timer = nullptr; QElapsedTimer m_interTick; }; } // namespace hmi- Qt::PreciseTimer disables default 5% CoarseTimer rounding on the 20 ms telemetry cadence.
- Passing 'this' as the 2nd argument to QTimer::singleShot cancels the 250 ms callback if FrameWatchdog is deleted early.
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 Lesson 3.3 QTimer-QElapsedTimer(3qt) GL-Q01 quick reference · full manual page: man 3qt QTimer-QElapsedTimer Proving Monotonic Phase-Lock, 5% Coarse Window & Paint Starvation in C++20
In verify.cpp, we invoke the Linux kernel SYS_clock_gettime syscall with CLOCK_MONOTONIC directly so strace captures the kernel monotonic clock read explicitly, then run a deterministic TimerLoop proving four invariants: (1) coarse_window_ns() computes Qt's 5% coalescing bound versus 0 for PreciseTimer; (2) late OS wakeups (21 ms, 42 ms, 61 ms) stay locked to the 20/40/60 ms phase grid; (3) a 75 ms blocking slot (61 -> 136 ms) starves queued paint requests during the stall and skips stale 80/100/120 ms ticks cleanly to 140 ms; and (4) destroying a context token cancels a pending single_shot timer before it fires!
learner@ksa:~/gl-q01/m03-l03$ bat -H 16 -H 63 verify.cpp File: verify.cpp #include <cassert> #include <cstdint> #include <cstdio> #include <ctime> #include <functional> #include <memory> #include <sys/syscall.h> #include <unistd.h> #include <vector> namespace hmi { enum class TimerMode { Precise, Coarse }; static std::uint64_t kernel_monotonic_ns() { timespec ts{}; const long rc = ::syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts); assert(rc == 0); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } static constexpr std::uint64_t coarse_window_ns(std::uint64_t period_ns, TimerMode mode) noexcept { return (mode == TimerMode::Coarse) ? (period_ns / 20ULL) : 0ULL; // 5% window } class TimerWheel { public: int add(std::uint64_t start_ns, std::uint64_t period_ns, bool single_shot, std::weak_ptr<bool> ctx, std::function<void(std::uint64_t)> cb) { const int id = m_next_id++; m_items.push_back({id, start_ns + period_ns, period_ns, single_shot, true, std::move(ctx), std::move(cb)}); return id; } int advance(std::uint64_t now_ns, bool &paint_pending, int &paints_rendered) { int fired = 0; for (;;) { Item *due = nullptr; for (auto &it : m_items) { if (!it.active || it.deadline_ns > now_ns) { continue; } if (!due || it.deadline_ns < due->deadline_ns || (it.deadline_ns == due->deadline_ns && it.id < due->id)) { due = ⁢ } } if (!due) { break; } auto alive = due->ctx.lock(); if (!alive || !*alive) { due->active = false; continue; } const std::uint64_t sched = due->deadline_ns; if (due->single_shot) { due->active = false; } else { do { due->deadline_ns += due->period_ns; } while (due->deadline_ns <= now_ns); } due->cb(sched); ++fired; } // Cooperative LowEventPriority paint runs ONLY after all due timer slots finish! if (paint_pending) { paint_pending = false; ++paints_rendered; } return fired; } std::uint64_t next_deadline(int id) const noexcept { for (const auto &it : m_items) { if (it.id == id && it.active) { return it.deadline_ns; } } return 0; } private: struct Item { int id; std::uint64_t deadline_ns; std::uint64_t period_ns; bool single_shot; bool active; std::weak_ptr<bool> ctx; std::function<void(std::uint64_t)> cb; }; int m_next_id = 1; std::vector<Item> m_items; }; } // namespace hmi int main() { constexpr std::uint64_t kMs = 1000000ULL; static_assert(hmi::coarse_window_ns(50 * kMs, hmi::TimerMode::Coarse) == 2500000ULL); static_assert(hmi::coarse_window_ns(50 * kMs, hmi::TimerMode::Precise) == 0ULL); const std::uint64_t t0 = hmi::kernel_monotonic_ns(); const std::uint64_t t1 = hmi::kernel_monotonic_ns(); assert(t1 >= t0); hmi::TimerWheel wheel; auto app_ctx = std::make_shared<bool>(true); auto popup_ctx = std::make_shared<bool>(true); bool paint_dirty = false; int paint_frames = 0; int cancelled_oneshot = 0; std::vector<std::uint64_t> grid_ms; const int pid = wheel.add(t0, 20 * kMs, false, app_ctx, [&] (std::uint64_t sched) { grid_ms.push_back((sched - t0) / kMs); paint_dirty = true; }); wheel.add(t0, 50 * kMs, true, popup_ctx, [&] (std::uint64_t) { ++cancelled_oneshot; }); wheel.advance(t0 + 21 * kMs, paint_dirty, paint_frames); *popup_ctx = false; // Destroy popup at 30 ms before 50 ms singleShot expires! wheel.advance(t0 + 42 * kMs, paint_dirty, paint_frames); wheel.advance(t0 + 61 * kMs, paint_dirty, paint_frames); assert((grid_ms == std::vector<std::uint64_t>{20, 40, 60})); assert(cancelled_oneshot == 0 && paint_frames == 3); // 75 ms GUI stall (61ms -> 136ms): misses 80/100/120 into 1 fire, next = 140ms! const int post_stall_fires = wheel.advance(t0 + 136 * kMs, paint_dirty, paint_frames); assert(post_stall_fires == 1 && paint_frames == 4); assert((wheel.next_deadline(pid) - t0) / kMs == 140); std::printf("Timer mono_dt=%lluns coarse50=%lluus grid=%zu oneshot_cancelled=%d next=%llums\n", static_cast<unsigned long long>(t1 - t0), static_cast<unsigned long long>( hmi::coarse_window_ns(50 * kMs, hmi::TimerMode::Coarse) / 1000ULL), grid_ms.size(), (cancelled_oneshot == 0) ? 1 : 0, static_cast<unsigned long long>((wheel.next_deadline(pid) - t0) / kMs)); return 0; }- Direct SYS_clock_gettime(CLOCK_MONOTONIC) syscall proves monotonic kernel clock anchor in strace.
- do { deadline_ns += period_ns; } while (deadline_ns <= now_ns) locks phase and skips stale stall multiples.
Inspecting CLOCK_MONOTONIC Syscalls and Post-Stall Phase Alignment
Inspect both ./verify stdout and the strace capture! ./verify prints coarse50=2500us grid=4 oneshot_cancelled=1 next=140ms: 5% of 50 ms equals 2500 us, destroying popup_ctx at 30 ms cancelled the 50 ms singleShot (oneshot_cancelled=1), and recovering at 136 ms from a 75 ms stall coalesced missed intervals into one callback and locked the next deadline to 140 ms.
In strace, confirm the two real clock_gettime(CLOCK_MONOTONIC, ...) kernel calls preceding write(1, ...) and exit_group(0).
learner@ksa:~/gl-q01/m03-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m03-l03./verifyTimer mono_dt=579ns coarse50=2500us grid=4 oneshot_cancelled=1 next=140mslearner@ksa:~/gl-q01/m03-l03learner@ksa:~/gl-q01/m03-l03strace -e trace=clock_gettime,write,exit_group \./verifyclock_gettime(CLOCK_MONOTONIC, {tv_sec=1136271, tv_nsec=834146}) = 0clock_gettime(CLOCK_MONOTONIC, {tv_sec=1136271, tv_nsec=893476}) = 0write(1, "Timer mono_dt=59330ns coarse50=2"..., 76) = 76exit_group(0) = ?+++ exited with 0 +++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 + QObject ownership trees, d_ptr + uic + moc void ** meta-dispatch, and PMF context lifetimes + LIFO eventFilter chains + CLOCK_MONOTONIC timers.
Complete the lab_m03_event_loop_timers studio below to integrate priority posted events, LIFO filters, and phase-locked monotonic timers into a single verified C++20 reactor library.
Starting an Unthrottled 0-ms Periodic QTimer (start(0)) on Embedded Linux:
- Symptom:
topshows the HMI binary pegged at100%CPU usage on oneCortex-A7core even when nothing on screen is changing, overheating the enclosure. - Root Cause: A
0 msperiodicQTimerfires every single time the event queue finishes draining normal events, preventingppoll()/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) orQSocketNotifierfd readiness.
Calling 2-Argument QTimer::singleShot(500, [this] { ... }) Without Receiver Context:
- 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-argumentQTimer::singleShot(msec, functor)has NO contextQObject *and fires unconditionally aftermseceven ifthiswas deleted! - Fix: Always call the 3-argument overload
QTimer::singleShot(500, this, [this] { ... })(or&Toast::fadeOut) so~Toast()cancels the timer automatically.
Guided Practice
Add a simulated NTP backward wall-clock jump (realtime_offset_ns -= 30 * 1000000000ULL) to verify.cpp alongside kernel_monotonic_ns(), and demonstrate in a short helper function why a wall-clock deadline hangs for 30 extra seconds while TimerWheel on CLOCK_MONOTONIC fires right on its 20 ms schedule.
Independent Practice
Open labs/lab_m03_event_loop_timers/ and repair all three defects in starter/core.cpp—inverted FIFO filter order, cumulative now_ns + period_ns timer drift, and missing receiver context-token cancellation—until sh check.sh passes 5/5 TAP version 13 checks and ./files/lab_cli --bench outputs CLOCK_MONOTONIC percentiles.
Verification Checks
? check 1 · 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?
- [ ] One timer tick every
10.5 ms(5%coarse window) via kernel preemption. - [x] Zero times during the
120 msscan, because the cooperative GUI thread never returns toexec(). - [ ] Twelve timer ticks via
SIGALRMinterrupts, whilepaintEventwaits until the end. - [ ] Twelve timer ticks and seven 60 Hz
paintEventframes on Qt's fallback render thread.
Answer: Zero times during the 120 ms scan, because the cooperative GUI thread never returns to exec().
Why: 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.
? check 2 · What is the default Qt::TimerType of a newly constructed QTimer, and how does it schedule intervals?
- [x]
Qt::CoarseTimer, which may adjust wakeups within a5%window of the interval to batch CPU wakeups. - [ ]
Qt::PreciseTimer, which busy-waits onCLOCK_MONOTONICfor sub-microsecond accuracy. - [ ]
Qt::VeryCoarseTimer, which rounds every interval below1000 msup to1full second. - [ ]
Qt::AutoConnection, which switches betweenCLOCK_REALTIMEandCLOCK_MONOTONIC.
Answer: Qt::CoarseTimer, which may adjust wakeups within a 5% window of the interval to batch CPU wakeups.
Why: 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.
? check 3 · Why is QTimer::singleShot(300, this, &Dialog::autoClose) safer than QTimer::singleShot(300, [this] { autoClose(); })?
- [ ] The 2-argument lambda overload uses
CLOCK_REALTIME, whereas the 3-argument overload usesCLOCK_MONOTONIC. - [ ] The 2-argument overload blocks the GUI thread synchronously for
300 mslikeusleep(). - [ ] Qt 6 deletes
Dialogimmediately when the 2-argumentsingleShotis scheduled. - [x] Passing
thisas the context object cancels the pending timer automatically ifDialogis destroyed before300 ms.
Answer: Passing this as the context object cancels the pending timer automatically if Dialog is destroyed before 300 ms.
Why: 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.
1. Motivation
Industrial HMIs fail intermittent soak tests when a safety eventFilter runs in the wrong order, periodic polling timers drift away from sensor frames using now + period, or a delayed singleShot callback fires onto a closed modal popup. In this studio you repair all three mechanisms inside hmi::ReactorLoop.
2. Learning objectives
- Dispatch installed
EventTargetfilters in LIFO order (rbegin()torend()) while compressing duplicateUpdateRequestposts. - Maintain zero-drift phase alignment (
deadline_ns += period_ns) with stale-interval skip-ahead and exact5%TimerKind::Coarsemath. - Check
EventTarget::life_token()before firing context-bound timers so destroyed receivers never experience use-after-free.
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7panel runningLinux kernel6.12 LTS and Qt 6.8 to measure realQElapsedTimerQt::PreciseTimerjitter understress-ngCPU load and WaylandQPaintEventcommits.
5. Complete executable commands
learner@ksa:~/gl-q01/m03-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/m03-l03$ bat example.cpp File: example.cpp if (due->has_ctx) { auto sp = due->ctx.lock(); if (!sp || !*sp) { due->active = false; // Receiver died; cancel callback cleanly! continue; } } const std::uint64_t sched = due->deadline_ns; if (due->single_shot || due->period_ns == 0) { due->active = false; } else { do { due->deadline_ns += due->period_ns; // Phase-locked + stale skip! } while (due->deadline_ns <= now_ns); }starter/core.cpp contains three classic reactor bugs: (1) ReactorLoop::send_event() iterates flts.begin()..flts.end() (FIFO) instead of rbegin()..rend() (LIFO); (2) ReactorLoop::step() computes due->deadline_ns = now_ns + due->period_ns, accumulating wakeup jitter; and (3) step() skips checking due->ctx.lock(), invoking callbacks after ~EventTarget().
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/m03-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - drains priority events, coalesces UpdateRequest, and runs event_filter in LIFO order ok 4 - computes 5ok 5 - auto-cancels timers bound to destroyed EventTarget contexts and honors cancel_timer # pass 5/5 check.sh: 36: printf: % C: invalid directiveCLI verification output (./files/lab_cli):
learner@ksa:~/gl-q01/m03-l03$ bat listing.txt File: listing.txt coarse_50ms_us=2500 ticks=1 paints=1 work=2Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
With LIFO traversal, phase-locked do-while deadline advancement, and weak_ptr context validation restored in files/core.cpp, sh check.sh compiles libcore.a cleanly under -std=c++20 -Wall -Wextra -Werror -pedantic and passes all 5/5 TAP version 13 assertions.
9. Experiment variations
- Near transfer: Add a
remove_filter(EventTarget *watcher)method toEventTarget(matchingQObject::removeEventFilter) and verify removing an active filter mid-session restores directon_eventdelivery. - Far transfer: Add a
next_sleep_ns(std::uint64_t now_ns)query toReactorLoopreturning0whenm_queueis non-empty or the deltaearliest_deadline - now_nssuitable for passing directly into Linuxepoll_pwait2().
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/m03-l03$ bat listing.txt File: listing.txt BENCH lab_m03_event_loop_timers clock=CLOCK_MONOTONIC benchmark_samples=40 warmup=5 p50_ns=72 p95_ns=73 p99_ns=73 sink=27000The CLOCK_MONOTONIC --bench percentiles measure one timer expiration, two coalesced UpdateRequest posts, and one send_event dispatch per step in host memory (p50 hundreds of nanoseconds). Never confuse host loop overhead with target ARMv7-A epoll_wait wakeup jitter or display controller VSync scanout periods.
11. Troubleshooting
| Symptom | Root cause | Fix | ||
|---|---|---|---|---|
not ok 3 - drains priority events... | ReactorLoop::send_event walked flts forward (FIFO) instead of reverse (LIFO). | Use for (auto it = flts.rbegin(); it != flts.rend(); ++it) so the last-installed filter runs first. | ||
not ok 4 - computes 5% CoarseTimer window... | Periodic rescheduling set now_ns + due->period_ns and drifted off the 125, 150, 175, 225 grid. | Advance do { due->deadline_ns += due->period_ns; } while (due->deadline_ns <= now_ns);. | ||
not ok 5 - auto-cancels timers bound to destroyed... | ReactorLoop::step() fired a single_shot timer whose EventTarget context had already been destroyed. | Check if (due->has_ctx) and verify `auto sp = due->ctx.lock(); if (!sp | !*sp) before calling due->cb`. |
12. Guided questions
- Why does
ReactorLoop::step()fire due timers BEFORE drainingm_queue(UpdateRequestat priority-1)?
- *Hint 1:* Think about what a
20 mstelemetry timer callback typically calls on gauges (update()). - *Hint 2:* Firing timers first lets all due timer callbacks update model state and post
UpdateRequest(-1), which then coalesces with any earlierUpdateRequestinto ONE single paint pass in the same turn!
- Why must periodic timer skip-ahead use
while (due->deadline_ns <= now_ns)rather than a singledue->deadline_ns += due->period_ns?
- *Hint 1:* What would happen after a
75 msstall on a25 mstimer (now_ns = 210,deadline_ns = 175) if you only added25once (200 <= 210)? - *Hint 2:* Adding
period_nsonly once leavesdeadline_ns = 200 <= 210, causing the loop to fire a burst of stale catch-up ticks back-to-back instead of resuming cleanly on the next future grid point (225)!
13. Independent challenges
Extend ReactorLoop::step() with a FrameStats return struct recording max_callback_ns and coalesced_updates using clock_gettime(CLOCK_MONOTONIC) around each due->cb(sched) call so unit tests can fail automatically if any callback exceeds a configurable budget.
14. Solutions and explanations
The reference files/core.cpp walks dst->filters() in reverse (rbegin()..rend()), advances periodic timers phase-locked via do { due->deadline_ns += due->period_ns; } while (due->deadline_ns <= now_ns);, and checks due->ctx.lock() prior to callback execution.
Run locally in your terminal and check off each verification milestone.
Not started
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.
Step sequence — frame strip: steps_m03_l03
Call setTimerType(Qt::PreciseTimer) before start() whenever +/-5% coarse jitter is unacceptable.
reveals: step1
highlights: step1
Pass 'this' as the 2nd argument to QTimer::singleShot so widget destruction cancels delayed slots.
reveals: step2
highlights: step2
Anchor periodic deadlines to the initial monotonic phase and skip past missed intervals after stalls.
reveals: step3
highlights: step3
Measure slot duration and inter-tick delta with QElapsedTimer to surface hidden main-thread stalls.
reveals: step4
highlights: step4
m04/
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.
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.
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 QToolButton, a pull-down maintenance QMenu item, and a physical F5 membrane key. Toggling setEnabled(false) on each widget separately during a safety fault invites a classic defect where the toolbar button turns grey while F5 remains active and starts motion.
QAction eliminates command drift by owning the authoritative enabled, checked, text, icon, and QKeySequence state in one object. Attaching that action via QToolButton::setDefaultAction(act) and menu->addAction(act) guarantees that act->setEnabled(false) locks every visual and keyboard surface atomically.
Physical panels add two tactile hazards that desktop apps ignore. Capacitive touch controllers resting under a gloved thumb trigger QAbstractButton::autoRepeat bursts unless setAutoRepeat(false) is set, and cramped 24x24 px desktop buttons cause cross-taps unless actuator hit boxes enforce at least 44x44 px (48x48 px recommended) minimum geometry.
Figure 4.1a. Actuator command path from touch target geometry through QButtonGroup and QAction interlocks.
mental model: 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.
definition (QButtonGroup & Two-Step Actuator Interlock): 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.
- Step 1. Attach mode QRadioButton controls to a QObject-based QButtonGroup so layout placement never breaks mutual exclusion.
- Step 2. Reflect mixed child zone enablement via QCheckBox::setCheckState(Qt::PartiallyChecked) without losing per-zone state.
- Step 3. Centralize shortcut and QToolButton enablement on QAction while enforcing 44x44 px touch targets and setAutoRepeat(false).
- Step 4. Use QDialogButtonBox semantic roles for fault-reset confirmation and force E-Stop recovery into Disarmed.
Figure 4.1b. Gate hazardous actions via Arm + QAction, disable autoRepeat, and size 44x44 px targets.
QButtonGroup Exclusivity, Tristate QCheckBox, and QDialogButtonBox Roles
Beginners often assume QRadioButton mutual exclusion requires wrapping buttons inside one QGroupBox. In Qt 6, QRadioButton auto-exclusivity groups siblings sharing the same parent QWidget, which breaks as soon as options sit in different container frames—or unintentionally links two unrelated radio pairs on the same panel! QButtonGroup inherits QObject directly, grouping arbitrary buttons by explicit integer ID (addButton(btn, id)) and emitting idClicked(int) without touching the visual layout.
When a parent control summarizes multiple child subsystems (such as four cooling-zone valves), a binary checkbox lies whenever two zones are open and two are closed. Calling QCheckBox::setTristate(true) unlocks Qt::PartiallyChecked (1) alongside Qt::Unchecked (0) and Qt::Checked (2), paired in Qt 6.8 with the strongly typed checkStateChanged(Qt::CheckState) signal.
Finally, distinguish clicked(bool) from toggled(bool) on checkable buttons, and use QDialogButtonBox (AcceptRole, RejectRole, DestructiveRole) on confirmation footers. Calling armBtn->setChecked(false) inside an E-Stop handler fires toggled(false) synchronously; wiring user arming to clicked(bool) ensures programmatic resets never re-enter command slots.
Figure 4.1b. Qt 6 button widget contracts, tristate rollup encodings, and semantic dialog roles.
| Qt 6 Control / Helper | Base Class | Primary Signal Contract | Embedded HMI Rule |
|---|---|---|---|
QPushButton | QAbstractButton (QWidget) | clicked(bool) (user) vs toggled(bool) (any) | Enforce >= 44x44 px min size and setAutoRepeat(false) on actuators |
QToolButton + QAction | QAbstractButton + QObject | QAction::triggered(bool) | Bind via setDefaultAction so shortcuts and buttons disable together |
QRadioButton + QButtonGroup | QAbstractButton + QObject | QButtonGroup::idClicked(int) | Assign explicit enum IDs; never rely on implicit parent-widget grouping |
QCheckBox (tristate) | QAbstractButton (QWidget) | checkStateChanged(Qt::CheckState) | Use Qt::PartiallyChecked for mixed child rollups; avoid deprecated stateChanged(int) |
QDialogButtonBox | QWidget | accepted(), rejected(), clicked(QAbstractButton*) | Assign semantic ButtonRole values instead of hardcoding OK/Cancel order |
learner@ksa:~/gl-q01/m04-l01$ bat -H 20 -H 70 interlock_button_panel.cpp File: interlock_button_panel.cpp #include <QAction> #include <QButtonGroup> #include <QCheckBox> #include <QDialogButtonBox> #include <QHBoxLayout> #include <QKeySequence> #include <QPushButton> #include <QRadioButton> #include <QToolButton> #include <QVBoxLayout> #include <QWidget> #include <array> class SpindleSafetyBar final : public QWidget { Q_OBJECT public: enum ModeId : int { ModeManual = 0, ModeAuto = 1, ModeJog = 2 }; explicit SpindleSafetyBar(QWidget *parent = nullptr) : QWidget(parent) { m_modeGroup = new QButtonGroup(this); // Non-visual QObject owner m_modeGroup->setExclusive(true); auto *modeRow = new QHBoxLayout(); const std::array<QString, 3> labels = {tr("&Manual"), tr("A&uto"), tr("&Jog")}; for (int id = 0; id < 3; ++id) { auto *rb = new QRadioButton(labels[static_cast<std::size_t>(id)], this); rb->setMinimumSize(44, 44); m_modeGroup->addButton(rb, id); modeRow->addWidget(rb); if (id == ModeManual) rb->setChecked(true); } m_coolantMaster = new QCheckBox(tr("Coolant Zones"), this); m_coolantMaster->setTristate(true); m_coolantMaster->setMinimumSize(44, 44); m_coolantMaster->setCheckState(Qt::PartiallyChecked); m_armBtn = new QPushButton(tr("&Arm Spindle"), this); m_armBtn->setCheckable(true); m_armBtn->setAutoRepeat(false); m_armBtn->setMinimumSize(48, 48); m_startAct = new QAction(tr("&Start Cycle"), this); m_startAct->setShortcut(QKeySequence(Qt::Key_F5)); m_startAct->setEnabled(false); m_startBtn = new QToolButton(this); m_startBtn->setDefaultAction(m_startAct); m_startBtn->setAutoRepeat(false); m_startBtn->setMinimumSize(48, 48); m_estopBtn = new QPushButton(tr("&E-Stop"), this); m_estopBtn->setAutoRepeat(false); m_estopBtn->setMinimumSize(56, 48); m_confirmBox = new QDialogButtonBox( QDialogButtonBox::Reset | QDialogButtonBox::Cancel, this); auto *actRow = new QHBoxLayout(); actRow->addWidget(m_coolantMaster); actRow->addWidget(m_armBtn); actRow->addWidget(m_startBtn); actRow->addWidget(m_estopBtn); auto *root = new QVBoxLayout(this); root->addLayout(modeRow); root->addLayout(actRow); root->addWidget(m_confirmBox); connect(m_armBtn, &QPushButton::clicked, this, [this](bool checked) { if (!m_tripped) m_startAct->setEnabled(checked); }); connect(m_startAct, &QAction::triggered, this, [this] { if (!m_tripped && m_armBtn->isChecked()) { m_armBtn->setChecked(false); m_startAct->setEnabled(false); emit cycleActuated(m_modeGroup->checkedId()); } }); connect(m_estopBtn, &QPushButton::clicked, this, &SpindleSafetyBar::tripEstop); } public slots: void tripEstop() { m_tripped = true; m_armBtn->setChecked(false); // Does NOT fire clicked(bool)! m_armBtn->setEnabled(false); m_startAct->setEnabled(false); emit emergencyTripped(); } signals: void cycleActuated(int modeId); void emergencyTripped(); private: bool m_tripped = false; QButtonGroup *m_modeGroup = nullptr; QCheckBox *m_coolantMaster = nullptr; QPushButton *m_armBtn = nullptr; QAction *m_startAct = nullptr; QToolButton *m_startBtn = nullptr; QPushButton *m_estopBtn = nullptr; QDialogButtonBox *m_confirmBox = nullptr; };- QButtonGroup parents to SpindleSafetyBar as a non-visual QObject, assigning stable ModeManual/Auto/Jog integer IDs.
- Connecting QPushButton::clicked (not toggled) ensures m_armBtn->setChecked(false) in tripEstop never re-triggers arming logic.
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 Lesson 4.1 QAbstractButton-QButtonGroup(3qt) GL-Q01 quick reference · full manual page: man 3qt QAbstractButton-QButtonGroup 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, subsystem tristate aggregation, minimum touch-box validation, auto-repeat rejection, and E-Stop fault recovery—can be proved deterministically in pure ISO C++20 without a display server.
Inspect verify.cpp below. ButtonGroupModel enforces single-selection invariants across integer IDs, compute_rollup derives Unchecked, PartiallyChecked, and Checked across four cooling zones, and InterlockHarness proves that held autoRepeat pulses are dropped and clearing an E-Stop returns to Disarmed rather than restoring a pre-fault Armed latch.
learner@ksa:~/gl-q01/m04-l01$ bat -H 27 -H 53 verify.cpp File: verify.cpp #include <array> #include <cassert> #include <cstdio> enum class CheckState : int { Unchecked = 0, PartiallyChecked = 1, Checked = 2 }; enum class Interlock : int { Disarmed = 0, Armed = 1, Tripped = 2 }; struct TouchBox { int width_px; int height_px; constexpr bool meets_hmi_minimum() const noexcept { return width_px >= 44 && height_px >= 44; } }; class ExclusiveButtonGroup { public: void add_button(int id, bool initial_checked) noexcept { if (id >= 0 && id < 4) { m_present[static_cast<std::size_t>(id)] = true; if (initial_checked || m_checked_id == -1) m_checked_id = id; } } bool click_id(int id) noexcept { if (id < 0 || id >= 4 || !m_present[static_cast<std::size_t>(id)]) return false; m_checked_id = id; return true; } int checked_id() const noexcept { return m_checked_id; } private: std::array<bool, 4> m_present{false, false, false, false}; int m_checked_id = -1; }; static CheckState rollup_zones(const std::array<bool, 4> &zones) noexcept { int on_count = 0; for (bool z : zones) { if (z) ++on_count; } if (on_count == 0) return CheckState::Unchecked; if (on_count == static_cast<int>(zones.size())) return CheckState::Checked; return CheckState::PartiallyChecked; } class InterlockHarness { public: bool start_action_enabled() const noexcept { return m_state == Interlock::Armed; } Interlock state() const noexcept { return m_state; } int actuations() const noexcept { return m_actuations; } int blocked_repeats() const noexcept { return m_blocked_repeats; } void user_click_arm(bool checked, bool is_auto_repeat = false) noexcept { if (is_auto_repeat) { ++m_blocked_repeats; return; } if (m_state != Interlock::Tripped) { m_state = checked ? Interlock::Armed : Interlock::Disarmed; } } bool trigger_start_action(bool is_auto_repeat = false) noexcept { if (is_auto_repeat) { ++m_blocked_repeats; return false; } if (!start_action_enabled()) return false; ++m_actuations; m_state = Interlock::Disarmed; // Consume single-cycle arm latch return true; } void press_estop() noexcept { m_state = Interlock::Tripped; } void acknowledge_reset() noexcept { if (m_state == Interlock::Tripped) m_state = Interlock::Disarmed; } private: Interlock m_state = Interlock::Disarmed; int m_actuations = 0; int m_blocked_repeats = 0; }; int main() { static_assert(!TouchBox{32, 48}.meets_hmi_minimum()); static_assert(TouchBox{48, 48}.meets_hmi_minimum()); ExclusiveButtonGroup modes; modes.add_button(0, true); modes.add_button(1, false); modes.add_button(2, false); assert(modes.checked_id() == 0); assert(modes.click_id(2) && modes.checked_id() == 2); assert(rollup_zones({false, false, false, false}) == CheckState::Unchecked); assert(rollup_zones({true, false, true, false}) == CheckState::PartiallyChecked); assert(rollup_zones({true, true, true, true}) == CheckState::Checked); InterlockHarness hmi; assert(!hmi.trigger_start_action(false)); hmi.user_click_arm(true, false); assert(hmi.start_action_enabled()); assert(!hmi.trigger_start_action(true)); // Held touch repeat rejected! assert(hmi.trigger_start_action(false)); assert(!hmi.start_action_enabled() && hmi.actuations() == 1); hmi.user_click_arm(true, false); hmi.press_estop(); assert(!hmi.start_action_enabled()); assert(!hmi.trigger_start_action(false)); hmi.acknowledge_reset(); assert(hmi.state() == Interlock::Disarmed && !hmi.start_action_enabled()); std::printf("buttons_audit: mode_id=%d tristate_part=%d actuations=%d repeats_blocked=%d reset_disarmed=%d\n", modes.checked_id(), static_cast<int>(rollup_zones({true, false, true, false})), hmi.actuations(), hmi.blocked_repeats(), hmi.state() == Interlock::Disarmed ? 1 : 0); return 0; }- Rollup returns PartiallyChecked (1) whenever 0 < active_zones < N, preserving mixed child state visibility.
- Consuming the Armed latch immediately on Start and forcing acknowledge_reset into Disarmed prevents unintended restart.
Verifying Interlock Transitions, Auto-Repeat Rejection, and Tristate Output
Compile and execute verify.cpp under strict -std=c++20 -Wall -Wextra -Werror -pedantic. Confirm the output reports mode_id=2 tristate_part=1 actuations=1 repeats_blocked=1 reset_disarmed=1, proving that un-armed start triggers fail, synthetic auto-repeat pulses increment repeats_blocked without actuating, and a valid start pulse consumes the arm latch immediately.
Notice the safety invariant verified at the end of main(): tripping E-Stop while Armed and then acknowledging the fault lands in Disarmed (reset_disarmed=1), never silently re-enabling Start.
learner@ksa:~/gl-q01/m04-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m04-l01./verifybuttons_audit: mode_id=2 tristate_part=1 actuations=1 repeats_blocked=1 reset_disarmed=1learner@ksa:~/gl-q01/m04-l01learner@ksa:~/gl-q01/m04-l01strace -e trace=write,exit_group ./verifywrite(1, "buttons_audit: mode_id=2 tristat"..., 89) = 89exit_group(0) = ?+++ exited with 0 +++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 styling begins. Keep logical grouping (QButtonGroup), command gating (QAction), and interactive versus programmatic signal semantics (clicked vs toggled) cleanly separated.
Remember the host-versus-target boundary: host C++20 verification proves state-machine transitions and >= 44x44 px geometry constraints, whereas capacitive touch jitter, wet-glove palm rejection, and physical E-Stop hardwired relay cutoffs must be validated on target hardware.
Connecting Checkable Actuator Logic to toggled(bool) Instead of clicked(bool):
- 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 ).
Relying on Parent-Widget Auto-Exclusivity for QRadioButton Sets:
- 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).
Guided Practice
Extend InterlockHarness in verify.cpp so trigger_start_action also requires ExclusiveButtonGroup::checked_id() to equal 1 (ModeAuto) while rejecting 0 (ModeManual) unless a separate deadman jog switch boolean is held. Assert that switching modes inside ExclusiveButtonGroup while Armed automatically clears the Armed latch back to Disarmed.
Independent Practice
Design a C++20 bidirectional tristate controller for an 8-channel alarm mask where clicking the parent CheckState cycles (Unchecked -> Checked, PartiallyChecked -> Checked, Checked -> Unchecked) across all 8 child channels, while toggling any single child recomputes the parent CheckState without losing individual channel flags.
Verification Checks
? check 1 · An engineer connects connect(armBtn, &QPushButton::toggled, this, &Panel::sendArmFrame) and calls armBtn->setChecked(false) inside an E-Stop handler. What happens?
- [ ]
setChecked(false)queues a deferred event that is dropped wheneverarmBtn->setEnabled(false)follows. - [ ] Compilation fails under Qt 6.8 unless
QSignalBlockeris passed toconnect(). - [x]
toggled(false)emits synchronously insidesetChecked(false)and invokessendArmFrame(false). - [ ] Nothing emits, because
toggled(bool)only fires on physical mouse, touch, or Spacebar clicks.
Answer: toggled(false) emits synchronously inside setChecked(false) and invokes sendArmFrame(false).
Why: 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).
? check 2 · Why bind a QToolButton, a QMenu entry, and an F5 shortcut to one shared QAction via setDefaultAction?
- [ ]
QActionautomatically enlarges all child buttons to64x64 pxregardless ofQSizePolicy. - [x] Calling
action->setEnabled(false)during a fault atomically disables the toolbar button, menu item, andF5shortcut together. - [ ]
QToolButtoncannot emitclicked()in Qt 6 unless a heap-allocatedQActionis attached first. - [ ]
QActionoffloads icon rasterization onto a dedicated worker thread outside the GUI thread.
Answer: Calling action->setEnabled(false) during a fault atomically disables the toolbar button, menu item, and F5 shortcut together.
Why: 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.
? check 3 · How does QButtonGroup allow mutually exclusive QRadioButton controls to sit inside different QHBoxLayout or QFrame containers?
- [x]
QButtonGroupis a non-visualQObjectthat tracks registered buttons and integer IDs independently of their visualQWidgetparents. - [ ]
QButtonGroupreparents every registeredQRadioButtoninto an invisible floatingQGroupBoxwindow. - [ ]
QButtonGrouprewritesQObject::parent()pointers tonullptrso layouts share ownership viastd::shared_ptr. - [ ]
QButtonGroupinterceptsLinux kernelevdevscan codes beforeQApplicationcreates widget events.
Answer: QButtonGroup is a non-visual QObject that tracks registered buttons and integer IDs independently of their visual QWidget parents.
Why: 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.
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.
Step sequence — frame strip: steps_m04_l01
Attach mode QRadioButton controls to a QObject-based QButtonGroup so layout placement never breaks mutual exclusion.
reveals: step1
highlights: step1
Reflect mixed child zone enablement via QCheckBox::setCheckState(Qt::PartiallyChecked) without losing per-zone state.
reveals: step2
highlights: step2
Centralize shortcut and QToolButton enablement on QAction while enforcing 44x44 px touch targets and setAutoRepeat(false).
reveals: step3
highlights: step3
Use QDialogButtonBox semantic roles for fault-reset confirmation and force E-Stop recovery into Disarmed.
reveals: step4
highlights: step4
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.
Prefix Validation Automata and Coupled-Control Signal Ping-Pong
Consider a manifold pressure QLineEdit constrained to [100, 500] kPa. A naive keystroke filter that rejects every integer below 100 makes typing '250' impossible because the very first keystroke '2' is less than 100! Qt's QValidator resolves this cleanly with three states: '25x' or '999' returns Invalid (discarded immediately), "" or '2' or '25' returns Intermediate (accepted into the buffer while suppressing editingFinished()), and '250' returns Acceptable.
A companion hazard lurks inside QSpinBox and QDoubleSpinBox: by default, keyboardTracking() is true, so typing '2', '5', '0' emits valueChanged on every valid intermediate keystroke! Calling setKeyboardTracking(false) withholds valueChanged until the operator presses Enter, leaves focus, or clicks an arrow step.
Once committed, dashboards often mirror one setpoint across a QSpinBox, a coarse QSlider or QDial, and a QLineEdit. Without QSignalBlocker, spin->setValue(243) updates slider to 240 (5-unit tick), which fires slider->valueChanged(240) right back to overwrite spin with 240!
Figure 4.2a. Keystroke validation and multi-widget setpoint synchronization without recursive signal echo.
mental model: 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.
definition ( & QValidator::State): 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++ guard calling m_wasBlocked = obj->blockSignals(true) in its constructor and obj->blockSignals(m_wasBlocked) in its destructor.
- Step 1. Let QValidator::Intermediate pass valid numeric prefixes without firing editingFinished prematurely.
- Step 2. Disable keyboardTracking on setpoint spinboxes so hardware sees only committed Enter, focus-out, or step clicks.
- Step 3. Wrap programmatic setValue/setText calls in stack-scoped QSignalBlocker guards to preserve outer block states.
- Step 4. Cap console RAM with QPlainTextEdit::setMaximumBlockCount and store QComboBox enum payloads via currentData().
Figure 4.2b. Gate commits on QValidator::Acceptable, sync peers with QSignalBlocker, and cap logs.
QSignalBlocker RAII, QPlainTextEdit vs QTextBrowser, and Typed Selectors
Legacy code often wraps programmatic updates in slider->blockSignals(true); slider->setValue(v); slider->blockSignals(false);. That pattern has two defects: an early return leaves the widget permanently mute, and blockSignals(false) unconditionally unblocks a widget that an outer diagnostic caller had intentionally silenced! const QSignalBlocker b(slider); captures the return value of blockSignals(true) and restores that exact prior boolean in ~QSignalBlocker().
For multi-line text, pick the engine that matches the workload. QTextEdit and read-only QTextBrowser construct a rich-text QTextDocument DOM supporting HTML tables, CSS, and hyperlinks—ideal for static help manuals, fatal for a 115200-baud serial trace! QPlainTextEdit uses a lightweight plain-text layout and setMaximumBlockCount(500), automatically evicting the oldest line block in O(1) when line 501 arrives.
Round out forms with typed selectors: pass QVariant integer IDs to QComboBox::addItem(tr("psi"), UnitPsi) and read combo->currentData().toInt() so switching UI languages never breaks unit math, and call QDateTimeEdit::setTimeZone(QTimeZone::UTC) so daylight-saving transitions never fold log query windows.
Figure 4.2b. Memory and precision contracts across Qt 6 text, numeric, selector, and log widgets.
| Editor / Display Class | Internal Backing Model | Critical Configuration Call | Primary HMI Use Case |
|---|---|---|---|
QLineEdit + QValidator | Single-line UTF-16 buffer | setValidator(new QIntValidator(lo, hi, this)) | Constrained codes, IP/hex tokens, validated numeric text |
QSpinBox / QDoubleSpinBox | Discrete int / double | setKeyboardTracking(false) | Precision stepped setpoints without mid-typing glitches |
QSlider / QDial | Bounded QAbstractSlider | Wrap programmatic setValue in QSignalBlocker | Coarse analog-style jog/trim mirrors coupled to spinboxes |
QComboBox + QDateTimeEdit | QStandardItemModel / QDateTime | addItem(text, enumVal) & setTimeZone(QTimeZone::UTC) | Translation-safe enum pickers and unambiguous UTC log filters |
QPlainTextEdit vs QTextBrowser | Plain blocks vs HTML QTextDocument | plain->setMaximumBlockCount(500) | Live streaming bus logs (Plain) vs hyperlinked help (Browser) |
learner@ksa:~/gl-q01/m04-l02$ bat -H 31 -H 83 coupled_setpoint_console.cpp File: coupled_setpoint_console.cpp #include <QComboBox> #include <QDateTime> #include <QDateTimeEdit> #include <QDial> #include <QHBoxLayout> #include <QIntValidator> #include <QLineEdit> #include <QPlainTextEdit> #include <QSignalBlocker> #include <QSlider> #include <QSpinBox> #include <QTimeZone> #include <QVBoxLayout> #include <QWidget> #include <algorithm> class CoupledSetpointConsole final : public QWidget { Q_OBJECT public: enum PressureUnit : int { UnitKpa = 1, UnitBarX100 = 2 }; static constexpr int kMinKpa = 100; static constexpr int kMaxKpa = 500; explicit CoupledSetpointConsole(QWidget *parent = nullptr) : QWidget(parent) { m_unitCombo = new QComboBox(this); m_unitCombo->addItem(tr("Kilopascals (kPa)"), UnitKpa); m_unitCombo->addItem(tr("Centibar (0.01 bar)"), UnitBarX100); m_spin = new QSpinBox(this); m_spin->setRange(kMinKpa, kMaxKpa); m_spin->setKeyboardTracking(false); // Commit only on Enter/focus-out/step m_slider = new QSlider(Qt::Horizontal, this); m_slider->setRange(kMinKpa, kMaxKpa); m_slider->setSingleStep(5); m_dial = new QDial(this); m_dial->setRange(kMinKpa, kMaxKpa); m_lineEdit = new QLineEdit(this); m_lineEdit->setValidator(new QIntValidator(kMinKpa, kMaxKpa, this)); m_utcFilter = new QDateTimeEdit(QDateTime::currentDateTimeUtc(), this); m_utcFilter->setTimeZone(QTimeZone::UTC); m_utcFilter->setDisplayFormat(QStringLiteral("yyyy-MM-dd HH:mm:ss 'UTC'")); m_logView = new QPlainTextEdit(this); m_logView->setReadOnly(true); m_logView->setMaximumBlockCount(500); // Bounded O(1) ring eviction auto *top = new QHBoxLayout(); top->addWidget(m_unitCombo); top->addWidget(m_spin); top->addWidget(m_slider); top->addWidget(m_dial); top->addWidget(m_lineEdit); top->addWidget(m_utcFilter); auto *root = new QVBoxLayout(this); root->addLayout(top); root->addWidget(m_logView); applySetpoint(250, false); connect(m_spin, &QSpinBox::valueChanged, this, [this](int v) { applySetpoint(v, true); }); connect(m_slider, &QSlider::valueChanged, this, [this](int v) { applySetpoint(v, true); }); connect(m_dial, &QDial::valueChanged, this, [this](int v) { applySetpoint(v, true); }); connect(m_lineEdit, &QLineEdit::editingFinished, this, [this] { bool ok = false; const int v = m_lineEdit->text().toInt(&ok); if (ok) applySetpoint(v, true); }); } signals: void setpointCommitted(int kpa, int unitEnum); private: void applySetpoint(int requestedKpa, bool emitBus) { const int clamped = std::clamp(requestedKpa, kMinKpa, kMaxKpa); if (clamped == m_kpa && emitBus) return; m_kpa = clamped; { const QSignalBlocker bSpin(m_spin); const QSignalBlocker bSlider(m_slider); const QSignalBlocker bDial(m_dial); const QSignalBlocker bEdit(m_lineEdit); m_spin->setValue(m_kpa); m_slider->setValue((m_kpa / 5) * 5); m_dial->setValue(m_kpa); m_lineEdit->setText(QString::number(m_kpa)); } if (emitBus) { const int unit = m_unitCombo->currentData().toInt(); m_logView->appendPlainText(QStringLiteral("COMMIT kpa=%1 unit=%2").arg(m_kpa).arg(unit)); emit setpointCommitted(m_kpa, unit); } } int m_kpa = 250; QComboBox *m_unitCombo = nullptr; QSpinBox *m_spin = nullptr; QSlider *m_slider = nullptr; QDial *m_dial = nullptr; QLineEdit *m_lineEdit = nullptr; QDateTimeEdit *m_utcFilter = nullptr; QPlainTextEdit *m_logView = nullptr; };- setKeyboardTracking(false) prevents partial keystrokes ('2', '25') from pulsing hardware setpoints before Enter.
- Four scoped QSignalBlocker instances silence coupled peer updates and restore prior blocked states before emit.
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 Lesson 4.2 QValidator-QSignalBlocker(3qt) GL-Q01 quick reference · full manual page: man 3qt QValidator-QSignalBlocker 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 [100, 500], anti-echo synchronization between an exact SpinBox and a 5-unit quantized Slider (including nested SignalBlocker preservation), and PlainLogRing eviction under a 4-block ceiling.
Examine RangeValidator::validate in verify.cpp: '2' and '25' have fewer digits than 500 (3 digits) so they classify as Intermediate, whereas '999' (> 500 at 3 digits), '-1' (lo >= 0), and '25a' classify immediately as Invalid.
learner@ksa:~/gl-q01/m04-l02$ bat -H 29 -H 72 verify.cpp File: verify.cpp #include <algorithm> #include <cassert> #include <cctype> #include <cstdio> #include <deque> #include <functional> #include <string> #include <string_view> enum class ValState { Invalid, Intermediate, Acceptable }; class RangeValidator { public: constexpr RangeValidator(int lo, int hi) noexcept : m_lo(lo), m_hi(hi) {} ValState validate(std::string_view s) const noexcept { if (s.empty()) return ValState::Intermediate; std::size_t i = 0; bool neg = false; if (s[0] == '+' || s[0] == '-') { neg = (s[0] == '-'); if ((neg && m_lo >= 0) || (!neg && m_hi < 0)) return ValState::Invalid; ++i; if (i == s.size()) return ValState::Intermediate; } long long v = 0; for (; i < s.size(); ++i) { const auto ch = static_cast<unsigned char>(s[i]); if (!std::isdigit(ch)) return ValState::Invalid; v = v * 10 + (ch - '0'); if (v > 1000000000LL) return ValState::Invalid; } const long long sv = neg ? -v : v; if (sv >= m_lo && sv <= m_hi) return ValState::Acceptable; if (!neg && m_hi >= 0 && sv < m_lo) { int hi_digits = 0; for (int t = m_hi; t > 0; t /= 10) ++hi_digits; const int cur_digits = static_cast<int>(s.size() - (s[0] == '+' ? 1U : 0U)); if (cur_digits < hi_digits) return ValState::Intermediate; } return ValState::Invalid; } private: int m_lo; int m_hi; }; class WidgetSignalNode { public: bool block_signals(bool b) noexcept { const bool prev = m_blocked; m_blocked = b; return prev; } bool signals_blocked() const noexcept { return m_blocked; } int value() const noexcept { return m_val; } void set_value(int v) { m_val = v; if (!m_blocked && on_value_changed) { ++emissions; on_value_changed(v); } } std::function<void(int)> on_value_changed; int emissions = 0; private: int m_val = 0; bool m_blocked = false; }; class ScopedSignalBlocker { public: explicit ScopedSignalBlocker(WidgetSignalNode &w) noexcept : m_w(w), m_prev(w.block_signals(true)) {} ~ScopedSignalBlocker() { m_w.block_signals(m_prev); } ScopedSignalBlocker(const ScopedSignalBlocker &) = delete; ScopedSignalBlocker &operator=(const ScopedSignalBlocker &) = delete; private: WidgetSignalNode &m_w; bool m_prev; }; class PlainLogRing { public: explicit PlainLogRing(std::size_t max_blocks) noexcept : m_max(max_blocks) {} void append_block(std::string line) { if (m_blocks.size() == m_max) m_blocks.pop_front(); m_blocks.push_back(std::move(line)); } std::size_t block_count() const noexcept { return m_blocks.size(); } const std::string &oldest() const { return m_blocks.front(); } private: std::size_t m_max; std::deque<std::string> m_blocks; }; int main() { constexpr RangeValidator val(100, 500); assert(val.validate("") == ValState::Intermediate); assert(val.validate("2") == ValState::Intermediate); assert(val.validate("25") == ValState::Intermediate); assert(val.validate("250") == ValState::Acceptable); assert(val.validate("500") == ValState::Acceptable); assert(val.validate("600") == ValState::Invalid); assert(val.validate("-5") == ValState::Invalid); assert(val.validate("25x") == ValState::Invalid); WidgetSignalNode spin; WidgetSignalNode slider; int bus_frames = 0; spin.on_value_changed = [&](int v) { const ScopedSignalBlocker guard(slider); slider.set_value((v / 5) * 5); ++bus_frames; }; slider.on_value_changed = [&](int v) { const ScopedSignalBlocker guard(spin); spin.set_value(v); ++bus_frames; }; spin.set_value(243); assert(spin.value() == 243 && slider.value() == 240); assert(spin.emissions == 1 && slider.emissions == 0 && bus_frames == 1); slider.block_signals(true); { const ScopedSignalBlocker nested(slider); slider.set_value(310); } assert(slider.signals_blocked()); PlainLogRing log(4); for (int i = 1; i <= 7; ++i) log.append_block("seq_" + std::to_string(i)); assert(log.block_count() == 4 && log.oldest() == "seq_4"); std::printf("editors_audit: spin=%d slider=%d commits=%d nested_kept=%d log_blocks=%zu oldest=%s\n", spin.value(), slider.value(), bus_frames, slider.signals_blocked() ? 1 : 0, log.block_count(), log.oldest().c_str()); return 0; }- Prefix strings shorter than m_hi's digit count return Intermediate so multi-keystroke entry reaches [100, 500].
- ScopedSignalBlocker saves block_signals(true)'s return value so nested callers never clobber an outer blocked state.
Inspecting Anti-Echo Counts, Validator Transitions, and Log Eviction
Run ./verify and confirm spin=243 slider=240 commits=1 nested_kept=1 log_blocks=4 oldest=seq_4. Setting spin to 243 quantized slider to 240 without firing slider.on_value_changed back into spin, emitted exactly 1 outbound bus commit, and preserved slider.signals_blocked() == true across the nested scope.
Meanwhile, appending 7 lines into PlainLogRing(4) capped memory at 4 blocks with seq_4 at the head—mirroring QPlainTextEdit::setMaximumBlockCount(4) on long-running embedded diagnostic consoles.
learner@ksa:~/gl-q01/m04-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m04-l02./verifyeditors_audit: spin=243 slider=310 commits=1 nested_kept=1 log_blocks=4 oldest=seq_4learner@ksa:~/gl-q01/m04-l02learner@ksa:~/gl-q01/m04-l02strace -e trace=write,exit_group ./verifywrite(1, "editors_audit: spin=243 slider=3"..., 85) = 85exit_group(0) = ?+++ exited with 0 +++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 data-entry panels deterministic across weeks of uptime. Next, Lesson 4.3 examines how Qt's geometry solvers position these editors across diverse screen resolutions without magic pixel coordinates.
Keep host-versus-target scope explicit: host C++20 tests verify validator automata and signal-graph invariants, whereas virtual on-screen keyboard (QtVirtualKeyboard) focus geometry and font metrics must be checked on the target panel.
Streaming Continuous Serial or CAN Logs into QTextEdit Without Block Caps:
- 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.
Matching QComboBox::currentText() Against English Literals:
- 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().
Guided Practice
Extend RangeValidator in verify.cpp to support signed negative temperature ranges [-40, -10] degrees Celsius. Test "", "-", "-2" (Acceptable or Intermediate? Careful: -2 > -10, yet typing '-', '2', '5' must pass through "-2" as Intermediate on the way to "-25"!) and verify both "-2" (Intermediate) and "-25" (Acceptable).
Independent Practice
Build a fixed-point CentibarSpinModel storing pressure in int32_t hundredths of a bar ([100, 500] -> 1.00 .. 5.00 bar) with exact string formatting and parsing ("2.45" <-> 245), proving that 10,000 consecutive +0.01 increments land at exact 10245 with zero floating-point rounding drift.
Verification Checks
? check 1 · With QIntValidator(100, 500) attached to a QLineEdit, what does validate("25", pos) return while the operator types '2', '5', '0'?
- [ ]
QValidator::Invalid, unlesssetKeyboardTracking(false)was called onQLineEdit. - [x]
QValidator::Intermediate, keeping"25"in the editor while withholdingeditingFinished(). - [ ]
QValidator::Invalid, rejecting'2'and'5'unless the full string"250"is pasted from the clipboard. - [ ]
QValidator::Acceptable, immediately clamping"25"to100and firingeditingFinished().
Answer: QValidator::Intermediate, keeping "25" in the editor while withholding editingFinished().
Why: 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.
? check 2 · Why is const QSignalBlocker b(widget); strictly safer than widget->blockSignals(true); ... widget->blockSignals(false);?
- [x]
QSignalBlockerrestores the widget's previoussignalsBlocked()boolean (not blindlyfalse) even across earlyreturnor exception paths. - [ ]
QSignalBlockeracquires an OS mutex so background threads can callwidget->setValue()concurrently. - [ ] Bare
blockSignals(true)permanently disconnects all PMFQObject::connectslots onwidget. - [ ]
QSignalBlockercompresses pendingQPaintEventregions insideQPlainTextEdit.
Answer: QSignalBlocker restores the widget's previous signalsBlocked() boolean (not blindly false) even across early return or exception paths.
Why: 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.
? check 3 · Which widget and configuration should display a continuous 200 lines/sec diagnostic UART trace on a 512 MiB embedded Linux panel?
- [ ]
QTextBrowsercallingsetHtml()on the accumulatedQStringbuffer every 50 ms. - [ ]
QTextEditwithsetAcceptRichText(true)so ANSI colors convert into nested HTML<span>nodes forever. - [ ]
QLineEditwithQValidator::Intermediateand verticalQSpacerItemwrapping. - [x]
QPlainTextEditwithsetReadOnly(true)andsetMaximumBlockCount(500).
Answer: QPlainTextEdit with setReadOnly(true) and setMaximumBlockCount(500).
Why: 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.
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.
Step sequence — frame strip: steps_m04_l02
Let QValidator::Intermediate pass valid numeric prefixes without firing editingFinished prematurely.
reveals: step1
highlights: step1
Disable keyboardTracking on setpoint spinboxes so hardware sees only committed Enter, focus-out, or step clicks.
reveals: step2
highlights: step2
Wrap programmatic setValue/setText calls in stack-scoped QSignalBlocker guards to preserve outer block states.
reveals: step3
highlights: step3
Cap console RAM with QPlainTextEdit::setMaximumBlockCount and store QComboBox enum payloads via currentData().
reveals: step4
highlights: step4
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.
Why Magic Pixel Coordinates Break and How QLayoutEngine Solves Constraints
Hardcoding btn->setGeometry(16, 420, 110, 36) looks fine on one workstation monitor at 96 DPI and breaks immediately in production: switching display panels from 1024x600 to 800x480, enabling 150% fractional scaling, or translating "Stop" into "Not-Aus" clips labels and overlaps neighbors.
Qt's layout engine (qGeomCalc) replaces fixed coordinates with a deterministic 1D/2D constraint solver. Each widget reports minimumSizeHint() (smallest unclipped size) and sizeHint() (natural preferred size), paired with QSizePolicy per axis (Fixed, Minimum, Preferred, Expanding, Ignored) and an optional integer stretch factor.
Walk the exact 1D equation for N_vis visible items inside width W with margins m_L, m_R and spacing s: usable span is U = W - m_L - m_R - (N_vis - 1) * s. Notice that hidden widgets (isVisible() == false) are skipped completely so hiding an alarm strip never leaves a double-spacing phantom gap!
Figure 4.3a. Constraint-based geometry calculation across visible items, size policies, and stretch remainders.
mental model: 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.
definition ( & Integer Stretch Solver): 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.
- Step 1. Compute usable span U from visible items only: hidden widgets contribute 0 px size and 0 spacing gaps.
- Step 2. Iteratively clamp items that hit maximumSize() so uncapped stretchable siblings absorb the leftover pixels.
- Step 3. Distribute integer division remainders deterministically so right/bottom edges align to the exact pixel.
- Step 4. Use QGridLayout for multi-column readouts, QFormLayout for 2-column inputs, and parentless nested sub-layouts.
Figure 4.3b. Ban magic setGeometry(); use QGridLayout/QFormLayout, QSizePolicy, and stretch weights.
Stretch Remainder Math, QGridLayout vs QFormLayout, and QSpacerItem
When usable width U exceeds the sum of clamped sizeHint() widths, QLayoutEngine allocates surplus S in strict priority tiers: items with positive stretch w_i > 0 split S proportionally (w_i / sum(w)); if all stretches are 0, QSizePolicy::Expanding items split S; if none are Expanding, Preferred items grow. Whenever a growing item hits maximumSize(), it saturates at maximumSize() and the remaining surplus redistributes iteratively across uncapped peers, finishing with 1-pixel remainder distribution.
Select the right container for 2D alignment. Stacking three separate QHBoxLayout rows for (Channel, Value, Unit) causes jagged vertical columns because each row's label has a different text width; QGridLayout unifies column 0 width to max(hint) while setColumnStretch(1, 1) sends every extra pixel into the readout column. For two-column parameter dialogs, QFormLayout::addRow(label, editor) handles label alignment and field growth automatically.
To push buttons to the right or bottom edge without allocating an empty QWidget, insert a QSpacerItem (or call box->addStretch(1)). And remember the golden parenting rule: pass this ONLY to the single root layout (new QVBoxLayout(this)), constructing nested child layouts parentless (new QHBoxLayout()) before attaching via root->addLayout(sub).
Figure 4.3b. Choosing between QBoxLayout, QGridLayout, QFormLayout, and QSpacerItem with QSizePolicy flags.
| Layout / Item Type | Dimensionality | Surplus Space Rule | Typical Engineering Pattern |
|---|---|---|---|
QHBoxLayout / QVBoxLayout | 1D horizontal or vertical | stretch > 0 first, then Expanding, then Preferred | Toolbars, action footers, vertical panel stacks |
QGridLayout | 2D (row, col, rowSpan, colSpan) | setColumnStretch(c, w) & setRowStretch(r, w) | Multi-channel (Name, Value, Unit) sensor matrices |
QFormLayout | 2-column (label, field) pairs | FieldGrowthPolicy (ExpandingFieldsGrow / AllNonFixedFieldsGrow) | Calibration offset, network, and serial-port forms |
QSpacerItem (addStretch) | Lightweight QLayoutItem | QSizePolicy::Expanding spring (0 QWidget overhead) | Right-aligning status badges or bottom-pinning footers |
learner@ksa:~/gl-q01/m04-l03$ bat -H 22 -H 44 calibration_layout_grid.cpp File: calibration_layout_grid.cpp #include <QFormLayout> #include <QGridLayout> #include <QHBoxLayout> #include <QLabel> #include <QPushButton> #include <QSizePolicy> #include <QSpacerItem> #include <QSpinBox> #include <QVBoxLayout> #include <QWidget> #include <array> class CalibrationTelemetryPanel final : public QWidget { Q_OBJECT public: explicit CalibrationTelemetryPanel(QWidget *parent = nullptr) : QWidget(parent) { auto *root = new QVBoxLayout(this); // Root layout owns child sub-layouts root->setContentsMargins(12, 10, 12, 10); root->setSpacing(10); // 1. 2D QGridLayout: aligns Name | Value | Unit columns across all 3 channels auto *grid = new QGridLayout(); // Parentless: attached via root->addLayout grid->setHorizontalSpacing(10); grid->setVerticalSpacing(6); const std::array<QString, 3> names = {tr("Manifold Pressure"), tr("Coolant Temp"), tr("Drive Current")}; const std::array<QString, 3> units = {QStringLiteral("kPa"), QStringLiteral("degC"), QStringLiteral("mA")}; for (int r = 0; r < 3; ++r) { auto *nameLbl = new QLabel(names[static_cast<std::size_t>(r)], this); nameLbl->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); auto *valLbl = new QLabel(QStringLiteral("0"), this); valLbl->setAlignment(Qt::AlignRight | Qt::AlignVCenter); valLbl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); auto *unitLbl = new QLabel(units[static_cast<std::size_t>(r)], this); unitLbl->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); grid->addWidget(nameLbl, r, 0); grid->addWidget(valLbl, r, 1); grid->addWidget(unitLbl, r, 2); } grid->setColumnStretch(0, 0); grid->setColumnStretch(1, 1); // Surplus horizontal width flows into column 1 grid->setColumnStretch(2, 0); root->addLayout(grid); // 2. 2-Column QFormLayout for calibration parameters auto *form = new QFormLayout(); auto *tareSpin = new QSpinBox(this); tareSpin->setRange(-100, 100); auto *alarmSpin = new QSpinBox(this); alarmSpin->setRange(100, 500); form->addRow(tr("&Zero Offset (kPa):"), tareSpin); form->addRow(tr("&Alarm Limit (kPa):"), alarmSpin); root->addLayout(form); // 3. Vertical QSpacerItem spring + right-aligned footer bar root->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); auto *footer = new QHBoxLayout(); footer->addStretch(1); // Horizontal QSpacerItem pushes Apply button flush right auto *applyBtn = new QPushButton(tr("&Apply Calibration"), this); applyBtn->setMinimumSize(44, 44); footer->addWidget(applyBtn); root->addLayout(footer); } };- Child sub-layouts (grid, form, footer) construct with no parent QWidget* and attach cleanly via root->addLayout().
- setColumnStretch(1, 1) routes all surplus width into the numeric value column while keeping labels and units compact.
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 Lesson 4.3 QLayout-QSizePolicy(3qt) GL-Q01 quick reference · full manual page: man 3qt QLayout-QSizePolicy Host C++20 Verifier for Stretch Remainders, Max-Cap Redistribution, and Hidden Items
Let us verify the exact integer math of qGeomCalc in verify.cpp: visible-only gap counting, iterative max_px saturation when one stretch sibling hits its ceiling, and remainder rounding across equal stretch weights so cumulative rounding drift is strictly zero.
Trace the three assertions before compiling: 322 px with 10 px margins across three stretch = 1 items (usable = 302, hints = 50*3 = 150, surplus = 152) yields [101, 101, 100] ending at exact 312 = 322 - 10; hiding the middle item removes one 8 px gap; and capping item 0 at 130 px transfers the leftover 70 px cleanly to item 1 (270 px).
learner@ksa:~/gl-q01/m04-l03$ bat -H 29 -H 79 verify.cpp File: verify.cpp #include <algorithm> #include <cassert> #include <cstdio> #include <vector> enum class Mode { Fixed, Preferred, Expanding }; struct Spec { int min_px; int hint_px; int max_px; int stretch; Mode mode; bool visible; }; struct Span { int pos = 0; int size = 0; }; static std::vector<Span> solve_axis(int total_px, int m_start, int m_end, int spacing, const std::vector<Spec> &items) { const int n = static_cast<int>(items.size()); std::vector<Span> out(static_cast<std::size_t>(n)); std::vector<int> vis; for (int i = 0; i < n; ++i) { if (items[static_cast<std::size_t>(i)].visible) vis.push_back(i); } if (vis.empty()) return out; const int gaps = (static_cast<int>(vis.size()) - 1) * spacing; const int avail = std::max(0, total_px - m_start - m_end - gaps); int sum = 0; for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; const int lo = (it.mode == Mode::Fixed) ? it.hint_px : it.min_px; const int hi = (it.mode == Mode::Fixed) ? it.hint_px : it.max_px; out[static_cast<std::size_t>(idx)].size = std::clamp(it.hint_px, lo, hi); sum += out[static_cast<std::size_t>(idx)].size; } int surplus = avail - sum; while (surplus > 0) { std::vector<int> w(static_cast<std::size_t>(n), 0); int w_sum = 0; for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; const int cur = out[static_cast<std::size_t>(idx)].size; if (it.mode != Mode::Fixed && it.stretch > 0 && cur < it.max_px) { w[static_cast<std::size_t>(idx)] = it.stretch; w_sum += it.stretch; } } if (w_sum == 0) { for (int idx : vis) { const auto &it = items[static_cast<std::size_t>(idx)]; if (it.mode == Mode::Expanding && out[static_cast<std::size_t>(idx)].size < it.max_px) { w[static_cast<std::size_t>(idx)] = 1; ++w_sum; } } } if (w_sum == 0) break; int gained = 0; bool capped = false; for (int idx : vis) { const int wi = w[static_cast<std::size_t>(idx)]; if (wi <= 0) continue; const int share = (surplus * wi) / w_sum; const int room = items[static_cast<std::size_t>(idx)].max_px - out[static_cast<std::size_t>(idx)].size; if (share >= room) { out[static_cast<std::size_t>(idx)].size += room; gained += room; capped = true; } else { out[static_cast<std::size_t>(idx)].size += share; gained += share; } } surplus -= gained; if (capped && gained > 0) continue; for (int idx : vis) { if (surplus <= 0) break; if (w[static_cast<std::size_t>(idx)] > 0 && out[static_cast<std::size_t>(idx)].size < items[static_cast<std::size_t>(idx)].max_px) { ++out[static_cast<std::size_t>(idx)].size; --surplus; } } break; } int cursor = m_start; for (int idx : vis) { out[static_cast<std::size_t>(idx)].pos = cursor; cursor += out[static_cast<std::size_t>(idx)].size + spacing; } return out; } int main() { const auto r_rem = solve_axis(322, 10, 10, 0, { {20, 50, 1000, 1, Mode::Expanding, true}, {20, 50, 1000, 1, Mode::Expanding, true}, {20, 50, 1000, 1, Mode::Expanding, true}, }); assert(r_rem[0].size == 101 && r_rem[1].size == 101 && r_rem[2].size == 100); assert(r_rem[2].pos + r_rem[2].size == 312); const auto r_hid = solve_axis(228, 10, 10, 8, { {40, 60, 500, 1, Mode::Expanding, true}, {40, 90, 500, 1, Mode::Expanding, false}, {40, 60, 500, 1, Mode::Expanding, true}, }); assert(r_hid[0].size == 100 && r_hid[1].size == 0 && r_hid[2].pos == 118); const auto r_cap = solve_axis(400, 0, 0, 0, { {50, 100, 130, 1, Mode::Expanding, true}, {50, 100, 1000, 1, Mode::Expanding, true}, }); assert(r_cap[0].size == 130 && r_cap[1].size == 270); std::printf("layout_audit: rem=[%d,%d,%d] end=%d hidden_pos2=%d capped=[%d,%d]\n", r_rem[0].size, r_rem[1].size, r_rem[2].size, r_rem[2].pos + r_rem[2].size, r_hid[2].pos, r_cap[0].size, r_cap[1].size); return 0; }- Gap count uses (vis.size() - 1) * spacing so hidden items leave zero orphan gaps between visible neighbors.
- When an item saturates max_px, looping continues so uncapped stretchable peers absorb the remaining surplus.
Verifying Exact Edge Alignment, Hidden-Item Gaps, and Cap Saturation
Confirm ./verify prints layout_audit: rem=[101,101,100] end=312 hidden_pos2=118 capped=[130,270]. Every pixel of the 302 px usable span was accounted for (101 + 101 + 100 = 302, landing flush at 312 = 322 - 10), the hidden middle item disappeared with zero extra 8 px gap (10 + 100 + 8 = 118), and saturating item 0 at 130 transferred all remaining width to item 1 (270).
Now proceed to lab_m04_box_grid_layout_solver to implement and benchmark both 1D deficit/surplus solving and 2D solve_grid track alignment.
learner@ksa:~/gl-q01/m04-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m04-l03./verifylayout_audit: rem=[101,101,100] end=312 hidden_pos2=118 capped=[130,270]learner@ksa:~/gl-q01/m04-l03learner@ksa:~/gl-q01/m04-l03strace -e trace=write,exit_group ./verifywrite(1, "layout_audit: rem=[101,101,100] "..., 73) = 73exit_group(0) = ?+++ exited with 0 +++Layout Parenting Errors and Minimum-Size Clipping Pitfalls
Constraint-driven layouts let a single Qt 6 widget hierarchy adapt cleanly across compact DIN-rail touchscreens, widescreen operator consoles, and localized translations without manual coordinate patches.
Keep the host-versus-target boundary clear: our CLOCK_MONOTONIC solver benchmark measures pure C++20 integer constraint solving in host RAM, whereas real glyph shaping (HarfBuzz) and high-DPI font hinting depend on the target rootfs font configuration.
Passing 'this' (QWidget *) to Nested Child Sub-Layouts:
- 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).
Allocating Empty QWidget Instances Instead of QSpacerItem Springs:
- 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).
Guided Practice
Extend solve_axis in verify.cpp to handle container shrinkage (surplus < 0, i.e., avail < sum) by subtracting deficit pixels from non-Fixed items down to their min_px floor. Test total_px = 140 with m_start = 10, m_end = 10, spacing = 0 (avail = 120) on {Fixed(50), Expanding(min=30, hint=60), Expanding(min=30, hint=60)} and confirm widths clamp cleanly to [50, 35, 35].
Independent Practice
Complete lab_m04_box_grid_layout_solver by repairing the three defects in starter/core.cpp: excluding hidden items from inter-item spacing gaps, looping max_px cap redistribution across uncapped siblings, and distributing integer remainders so pos + size matches total_px - margin_end.
Verification Checks
? check 1 · An engineer writes auto *root = new QVBoxLayout(this); auto *row = new QHBoxLayout(this); root->addLayout(row);. Why does Qt emit a runtime layout warning?
- [x] Passing
thistoQHBoxLayout(this)attempts to install a second top-level layout ontothis; nested layouts must be constructed parentless (new QHBoxLayout()). - [ ]
QVBoxLayoutcannot nestQHBoxLayoutinstances without an intermediateQFramewrapper widget. - [ ]
addLayout()requiresstd::move(row)under-std=c++20becauseQLayoutdisables copy construction. - [ ]
QHBoxLayoutmust be constructed BEFOREQVBoxLayoutwhenever both reference the sameQWidget.
Answer: Passing this to QHBoxLayout(this) attempts to install a second top-level layout onto this; nested layouts must be constructed parentless (new QHBoxLayout()).
Why: 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.
? check 2 · 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?
- [ ]
3gaps (30 pxtotal), becausew2remains in the layout item list at0 pxwidth with gaps on both sides. - [ ]
0gaps, because hiding any child widget resetsQHBoxLayout::spacing()to zero untilupdate()runs. - [ ]
4gaps (40 pxtotal), because Qt adds half-spacing padding tocontentsMargins()on hide events. - [x]
2gaps (20 pxtotal), computed from(3 visible widgets - 1) * 10.
Answer: 2 gaps (20 px total), computed from (3 visible widgets - 1) * 10.
Why: 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.
? check 3 · Three visible items in a QHBoxLayout all have stretch = 0: two use QSizePolicy::Preferred and one uses QSizePolicy::Expanding. How is surplus width distributed?
- [ ] All three split the surplus equally (
1/3each) wheneverstretch == 0. - [ ] The two
Preferreditems split the surplus equally whileExpandingshrinks tominimumSizeHint(). - [x] The
QSizePolicy::Expandingitem claims the surplus width beforePreferredsiblings grow. - [ ] All three remain stuck at
sizeHint()becausestretch == 0forbids growth abovesizeHint().
Answer: The QSizePolicy::Expanding item claims the surplus width before Preferred siblings grow.
Why: 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.
1. Motivation
Build and benchmark a deterministic ISO C++20 1D/2D box-and-grid layout geometry solver that mirrors QLayoutEngine (qGeomCalc) across hidden items, max_px saturation, and zero-drift remainder rounding.
2. Learning objectives
- Eliminate 1–2 px right-edge rounding gaps by distributing integer division remainders deterministically across active stretch items.
- Exclude hidden (
visible == false) widgets from both span sums and(N_visible - 1) * spacinggap deductions. - Redistribute surplus pixels iteratively when a stretchable item saturates
max_px, and align multi-row 2Dsolve_gridtracks.
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7HMI panel (800x480RGB LCD or1024x600LVDS) runningLinux kernel6.12 LTS and Qt 6.8QtWidgets, verified across96 DPIand144 DPIfont-scaling profiles.
5. Complete executable commands
learner@ksa:~/gl-q01/m04-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/m04-l03$ bat example.cpp File: example.cpp const int gaps = (static_cast<int>(vis.size()) - 1) * spacing; const int avail = std::max(0, total_px - margin_start - margin_end - gaps); // ... surplus -= gained; if (capped_any && gained > 0) { continue; // Re-run proportional split across remaining uncapped siblings! } for (int idx : vis) { if (surplus <= 0) break; if (weights[static_cast<std::size_t>(idx)] > 0 && result[static_cast<std::size_t>(idx)].size < items[static_cast<std::size_t>(idx)].max_px) { ++result[static_cast<std::size_t>(idx)].size; --surplus; } }starter/core.cpp contains three realistic layout bugs: gaps multiplies (n - 1) * spacing across hidden items, capped_any fails to re-enter the redistribution loop when an item saturates max_px, and modulo remainder pixels are discarded instead of distributed.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/m04-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - distributes proportional stretch weights and 1px modulo remainders with zero cumulative drift ok 4 - excludes hidden items from both pixel allocation and inter-item spacing gap counts ok 5 - redistributes leftover surplus when a stretch item hits max_px and aligns 2D grid tracks # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-q01/m04-l03$ bat listing.txt File: listing.txt box_322px: [101, 101, 100] right_edge=312 grid_430x100: col0_w=110 col1_x=130 col1_w=290Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
Check 3 divides 152 surplus pixels across three equal stretch = 1 items (50 + 51, 50 + 51, 50 + 50), verifying the right edge lands at exact 312 = 322 - 10. Check 4 hides item 1 inside a 3-item box, confirming only one 8 px gap separates items 0 and 2. Check 5 caps item 0 at 130 px in a 400 px span (routing all 270 px to item 1) and aligns 2D grid columns across unequal label widths (80 vs 110).
9. Experiment variations
- Near transfer: Add
col_spansupport (col_span == 2) toGridCellso a section header banner spans columns0..1with widthx_tracks[0].size + h_spacing + x_tracks[1].size. - Far transfer: Implement
QFormLayout-style two-column row solving where right-aligned column-0labels lock to the widest label'shint_pxwhile column-1editors expand up tomax_px.
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/m04-l03$ bat listing.txt File: listing.txt bench_layout_solver_ns: p50=330 p95=340 p99=356 (sink=24468390)The CLOCK_MONOTONIC benchmark measures user-space C++20 2D grid constraint solving (nanoseconds per 2x2 solve in host DRAM). Target frame-time budgets on Cortex-A7 must also include QFontMetrics glyph measurement and QPainter backing-store rasterization.
11. Troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
| Check 3 fails with right_edge=310 instead of 312 | Starter code zeroes surplus instead of distributing 1px remainders | Increment uncapped weighted items by 1px while surplus > 0 |
| Check 4 fails with pos2=114 and sizes=[96,0,96] | gaps used total item count n (2 gaps = 16px) instead of vis.size() (1 gap = 8px) | Compute gaps = (static_cast<int>(vis.size()) - 1) * spacing |
| Check 5 fails with [130, 250] instead of [130, 270] | While loop exited after item 0 hit max_px=130 without redistributing remaining 20px | Keep if (capped_any && gained > 0) continue; active before remainder loop |
12. Guided questions
- Why must max_px saturation run inside a while(surplus > 0) loop rather than a single pass?
- *Hint 1:* Suppose 3 items have stretch 1:1:1 with surplus 300, item 0 caps at +30, and item 1 caps at +110.
- *Hint 2:* Pass 1 caps item 0 (+30), leaving 270 for items 1 and 2 (+135 each), which then triggers item 1's +110 cap on pass 2 so item 2 receives the final +160.
- Why does QSpacerItem avoid the memory and event overhead of an empty QWidget?
- *Hint 1:* Check the inheritance hierarchy of QSpacerItem versus QWidget.
- *Hint 2:* QSpacerItem inherits QLayoutItem directly (not QObject or QWidget), participating in geometry math with zero window-system or event-dispatch state.
13. Independent challenges
Extend solve_box_axis with proportional shrink priorities (SizeMode::Expanding shrinks faster than Preferred, while Fixed never shrinks below hint_px) and verify across 100 randomized container widths that no item ever violates [eff_min, eff_max].
14. Solutions and explanations
Filtering visible items first, iterating max_px saturation until only uncapped items remain, and distributing modulo remainder pixels guarantee drift-free 1D and 2D layout geometry.
Run locally in your terminal and check off each verification milestone.
Not started
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().
Step sequence — frame strip: steps_m04_l03
Compute usable span U from visible items only: hidden widgets contribute 0 px size and 0 spacing gaps.
reveals: step1
highlights: step1
Iteratively clamp items that hit maximumSize() so uncapped stretchable siblings absorb the leftover pixels.
reveals: step2
highlights: step2
Distribute integer division remainders deterministically so right/bottom edges align to the exact pixel.
reveals: step3
highlights: step3
Use QGridLayout for multi-column readouts, QFormLayout for 2-column inputs, and parentless nested sub-layouts.
reveals: step4
highlights: step4
m05/
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.
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.
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 switching among Run, Alarms, Trends, I/O Matrix, Calibration, and P&ID Schematic screens (while desktop engineering tools expose QTabWidget tabs, QToolBox accordions, QDockWidget sidebars, or multi-window QMdiArea workspaces). Constructing every screen eagerly inside MainWindow wastes hundreds of milliseconds at cold boot and pins megabytes of idle QWidgetPrivate trees in RAM.
Registering lightweight std::function<QWidget *(QWidget *)> factories per slot lets MainWindow build only page 0 before showing its first frame. When a technician taps P&ID Schematic, the deck invokes that slot's factory once, splices the real widget into QStackedWidget at the exact index, removeWidgets the placeholder stub, and calls delete oldStub so zero orphan QObject children linger.
Inside tall configuration pages, QScrollArea clips a large child widget through a scrollable viewport(). Crucially, QScrollArea::widgetResizable() defaults to false—omitting setWidgetResizable(true) leaves inner layouts frozen at their initial sizeHint() even when the panel widens to 1920 px!
Figure 5.1a. Cold-boot memory and startup latency savings from lazy QStackedWidget page materialization.
mental model: 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.
definition (Lazy QStackedWidget Factory & Viewport Containers): 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.
- Step 1. Populate off-screen QStackedWidget indices with empty QWidget stubs so cold boot builds only page 0.
- Step 2. Materialize the target page on first visit and explicitly delete the detached placeholder QWidget.
- Step 3. Always call setWidgetResizable(true) after QScrollArea::setWidget() so inner responsive layouts expand.
- Step 4. Pin telemetry QLabel instances to Qt::PlainText and reserve QGraphicsView for 2D coordinate scenes.
Figure 5.1b. Build hidden pages lazily, delete stubs, setWidgetResizable(true), and use PlainText.
Passive Display Hardening, Checkable QGroupBox, and QGraphicsView Overview
Passive display widgets carry subtle defaults worth knowing cold. QLabel defaults to Qt::AutoText, which scans every string with Qt::mightBeRichText(): if a raw serial packet contains "RX <ACK>", QLabel switches to an HTML parser and swallows <ACK> as an unknown tag! Always set label->setTextFormat(Qt::PlainText) on dynamic telemetry labels. Pair QFrame (HLine/StyledPanel) and QProgressBar (setRange(0, 0) for indeterminate busy states, explicit [min, max] otherwise) with monospace QLabel readouts rather than legacy QLCDNumber seven-segment polygons on modern high-DPI screens.
For collapsible or optional parameter blocks, QGroupBox::setCheckable(true) automatically enables or disables every child widget inside the group box when its title checkbox is toggled. On multi-monitor commissioning laptops, QMainWindow::saveState() and QSplitter::saveState() serialize QDockWidget positions and splitter ratios into a QByteArray for instant session restore.
When a screen must pan, zoom, and hit-test thousands of interactive 2D symbols—such as valve P&ID diagrams, PCB footprints, or state-machine wires—QLayout is the wrong abstraction. QGraphicsScene stores lightweight non-QWidget QGraphicsItem primitives indexed by a Binary Space Partitioning (BSP) tree, rendered through one or more zoomed/rotated QGraphicsView viewports.
Figure 5.1b. Architectural boundaries across Qt 6 display widgets, multi-page containers, and 2D graphics views.
| Container / Display Class | Child Ownership / Model | Key Pitfall / Configuration | Ideal Workload |
|---|---|---|---|
QStackedWidget / QTabWidget | QObject child QWidget pages | removeWidget(w) keeps QObject parent; call delete w | Primary touchscreen screen decks and tabbed dialogs |
QScrollArea | Single inner widget() inside viewport() | Defaults to widgetResizable() == false; set true! | Tall parameter forms on compact 800x480 panels |
QToolBox / checkable QGroupBox | Accordion pages / grouped child controls | Toggling checkable QGroupBox disables all children | Categorized inspector drawers and optional subsystem enables |
QDockWidget / QMdiArea | Dockable panes / QMdiSubWindow frames | Persist geometry via QMainWindow::saveState() | Desktop calibration & logic-analyzer workbenches |
QGraphicsView + QGraphicsScene | Lightweight non-widget QGraphicsItems | Disable BSP re-indexing during bulk dynamic moves | Zoomable P&ID piping diagrams and 2D node canvases |
learner@ksa:~/gl-q01/m05-l01$ bat -H 35 -H 85 lazy_workbench_containers.cpp File: lazy_workbench_containers.cpp #include <QDockWidget> #include <QFrame> #include <QGraphicsRectItem> #include <QGraphicsScene> #include <QGraphicsView> #include <QGroupBox> #include <QHBoxLayout> #include <QLabel> #include <QMainWindow> #include <QProgressBar> #include <QScrollArea> #include <QStackedWidget> #include <QVBoxLayout> #include <QWidget> #include <functional> #include <vector> class LazyWorkbenchWindow final : public QMainWindow { Q_OBJECT public: using PageFactory = std::function<QWidget *(QWidget *parent)>; explicit LazyWorkbenchWindow(QWidget *parent = nullptr) : QMainWindow(parent) { m_stack = new QStackedWidget(this); setCentralWidget(m_stack); // Status dock with PlainText QLabel + QProgressBar inside a styled QFrame auto *dock = new QDockWidget(tr("Telemetry Bus"), this); dock->setObjectName(QStringLiteral("TelemetryBusDock")); // Required for saveState()! auto *frame = new QFrame(dock); frame->setFrameShape(QFrame::StyledPanel); m_rawBusLabel = new QLabel(QStringLiteral("IDLE <NO_HTML>"), frame); m_rawBusLabel->setTextFormat(Qt::PlainText); // Never parse '<...>' as HTML! m_loadBar = new QProgressBar(frame); m_loadBar->setRange(0, 100); m_loadBar->setValue(18); auto *dockLay = new QVBoxLayout(frame); dockLay->addWidget(m_rawBusLabel); dockLay->addWidget(m_loadBar); dock->setWidget(frame); addDockWidget(Qt::RightDockWidgetArea, dock); // Page 0 (eager): scrollable groupbox form; Page 1 (lazy): QGraphicsView P&ID scene registerPage([](QWidget *p) { auto *content = new QWidget(); auto *lay = new QVBoxLayout(content); auto *grp = new QGroupBox(tr("Enable Heater Loop"), content); grp->setCheckable(true); lay->addWidget(grp); auto *scroll = new QScrollArea(p); scroll->setWidget(content); scroll->setWidgetResizable(true); // Critical: stretches content to viewport! return scroll; }, true); registerPage([](QWidget *p) { auto *scene = new QGraphicsScene(p); scene->addRect(0.0, 0.0, 180.0, 90.0); auto *view = new QGraphicsView(scene, p); view->setRenderHint(QPainter::Antialiasing, true); return view; }, false); } int registerPage(PageFactory factory, bool buildNow) { const int idx = static_cast<int>(m_slots.size()); auto *stub = new QWidget(m_stack); m_stack->addWidget(stub); m_slots.push_back({std::move(factory), stub, false}); if (buildNow) switchToPage(idx); return idx; } void switchToPage(int idx) { if (idx < 0 || idx >= static_cast<int>(m_slots.size())) return; Slot &s = m_slots[static_cast<std::size_t>(idx)]; if (!s.built && s.factory) { QWidget *real = s.factory(m_stack); QWidget *oldStub = s.widget; m_stack->insertWidget(idx, real); m_stack->removeWidget(oldStub); delete oldStub; // Mandatory: removeWidget leaves m_stack as QObject parent! s.widget = real; s.built = true; } m_stack->setCurrentIndex(idx); } private: struct Slot { PageFactory factory; QWidget *widget = nullptr; bool built = false; }; QStackedWidget *m_stack = nullptr; QLabel *m_rawBusLabel = nullptr; QProgressBar *m_loadBar = nullptr; std::vector<Slot> m_slots; };- setTextFormat(Qt::PlainText) stops QLabel::Qt::AutoText from swallowing '<NO_HTML>' bracket tokens.
- Explicit delete oldStub after removeWidget prevents orphan placeholder QWidgets from accumulating under m_stack.
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 Lesson 5.1 QStackedWidget-QScrollArea(3qt) GL-Q01 quick reference · full manual page: man 3qt QStackedWidget-QScrollArea Host C++20 Verifier for Lazy Deck RAM Budgets, Stub Cleanup, and Scroll Viewports
In verify.cpp, we model an 8-screen LazyStackDeck tracking both resident page memory and live placeholder stubs (live_stubs), alongside a ScrollAreaViewport verifier contrasting widget_resizable = false against true and testing raw <ACK> plain-text preservation.
Verify the memory trajectory: registering 8 screens of 256 KiB each with only page 0 eager consumes 256 KiB (7 stubs alive) instead of 2,048 KiB, and visiting screen 5 twice raises resident bytes to 512 KiB (6 stubs alive, factory_builds == 2).
learner@ksa:~/gl-q01/m05-l01$ bat -H 26 -H 58 verify.cpp File: verify.cpp #include <algorithm> #include <cassert> #include <cstddef> #include <cstdio> #include <functional> #include <memory> #include <string> #include <vector> struct BuiltPage { std::string name; std::size_t ram_bytes; }; class LazyStackDeck { public: using Factory = std::function<std::unique_ptr<BuiltPage>()>; int register_page(Factory fn, bool eager) { const int idx = static_cast<int>(m_slots.size()); m_slots.push_back({std::move(fn), true, nullptr}); ++m_live_stubs; if (eager) activate(idx); return idx; } void activate(int idx) { assert(idx >= 0 && idx < static_cast<int>(m_slots.size())); auto &s = m_slots[static_cast<std::size_t>(idx)]; if (!s.page) { s.page = s.factory(); ++m_builds; if (s.has_stub) { s.has_stub = false; --m_live_stubs; // Mirrors removeWidget(stub) + delete stub! } } m_current = idx; } std::size_t resident_bytes() const noexcept { std::size_t total = 0; for (const auto &s : m_slots) { if (s.page) total += s.page->ram_bytes; } return total; } int builds() const noexcept { return m_builds; } int live_stubs() const noexcept { return m_live_stubs; } int current() const noexcept { return m_current; } private: struct Slot { Factory factory; bool has_stub; std::unique_ptr<BuiltPage> page; }; std::vector<Slot> m_slots; int m_builds = 0; int m_live_stubs = 0; int m_current = -1; }; struct ScrollAreaViewport { int viewport_w; int viewport_h; int hint_w; int content_h; bool widget_resizable; int content_width() const noexcept { return widget_resizable ? std::max(viewport_w, hint_w) : hint_w; } int clamp_scroll_y(int y) const noexcept { return std::clamp(y, 0, std::max(0, content_h - viewport_h)); } }; int main() { LazyStackDeck deck; for (int i = 0; i < 8; ++i) { deck.register_page( [i] { return std::make_unique<BuiltPage>( BuiltPage{"screen_" + std::to_string(i), std::size_t{256} * 1024U}); }, i == 0); } assert(deck.current() == 0 && deck.builds() == 1 && deck.live_stubs() == 7); assert(deck.resident_bytes() == std::size_t{256} * 1024U); deck.activate(5); deck.activate(5); // Cached: must not rebuild! assert(deck.builds() == 2 && deck.live_stubs() == 6); assert(deck.resident_bytes() == std::size_t{512} * 1024U); constexpr ScrollAreaViewport frozen{1024, 480, 340, 1400, false}; constexpr ScrollAreaViewport fluid{1024, 480, 340, 1400, true}; assert(frozen.content_width() == 340); assert(fluid.content_width() == 1024 && fluid.clamp_scroll_y(1200) == 920); std::printf("containers_audit: boot_kib=256 active_kib=%zu builds=%d stubs=%d scroll_w=%d max_y=%d\n", deck.resident_bytes() / 1024U, deck.builds(), deck.live_stubs(), fluid.content_width(), fluid.clamp_scroll_y(1200)); return 0; }- Activating an unbuilt slot runs its factory once and decrements m_live_stubs (mirroring delete oldStub).
- With widget_resizable=true, inner content expands to viewport_w (1024 px) instead of staying stuck at 340 px.
Verifying Startup Memory Savings, Stub Deletion, and Viewport Expansion
Run ./verify and confirm containers_audit: boot_kib=256 active_kib=512 builds=2 stubs=6 scroll_w=1024 max_y=920. Lazy page factories cut startup allocation by 8x (256 KiB vs 2,048 KiB), revisiting page 5 reused the live instance (builds=2), and widget_resizable = true expanded inner form width to 1024 px.
Next, what happens inside an Alarms or Telemetry page when 50,000 records must be displayed? Even a lazy page freezes if populated with convenience item-widgets—leading directly to Lesson 5.2.
learner@ksa:~/gl-q01/m05-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m05-l01./verifycontainers_audit: boot_kib=256 active_kib=512 builds=2 stubs=6 scroll_w=1024 max_y=920learner@ksa:~/gl-q01/m05-l01learner@ksa:~/gl-q01/m05-l01strace -e trace=write,exit_group ./verifywrite(1, "containers_audit: boot_kib=256 a"..., 87) = 87exit_group(0) = ?+++ exited with 0 +++Production Bugs with QScrollArea, removeWidget, and QMainWindow::saveState
Lazy container decks bound page-level memory while QScrollArea, QDockWidget, and QGraphicsView partition layout forms, detachable panes, and 2D world scenes cleanly.
Keep host-versus-target evidence separate: host C++20 accounting proves page-allocation counts and viewport math, whereas target cold-boot latency (time_to_first_frame) must be profiled on the embedded board with real shared libraries and fonts.
Forgetting scrollArea->setWidgetResizable(true) on Responsive Forms:
- 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).
Calling QMainWindow::saveState() Without Unique QDockWidget::setObjectName():
- 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.
Guided Practice
Add an evict_inactive_lru() method to LazyStackDeck in verify.cpp that enforces a strict 768 KiB (3-page) resident RAM ceiling on ultra-constrained panels: if activating a fourth page exceeds 768 KiB, destroy the least-recently-visited non-current page (page.reset(); has_stub = true; ++m_live_stubs;) and verify resident_bytes() <= 768 * 1024 across all 8 pages.
Independent Practice
Write a C++20 PlainVsAutoText sanitizer check modeling QLabel default AutoText detection (< followed by > on the same line) and prove which raw NMEA-0183 or diagnostic strings ("RX <NAK> 0x15") would trigger rich-text corruption if Qt::PlainText were omitted.
Verification Checks
? check 1 · After calling m_stack->insertWidget(idx, realPage) and m_stack->removeWidget(oldStub) on a QStackedWidget, why is delete oldStub; still required?
- [ ]
removeWidget()is a no-op in Qt 6 unlessQSignalBlockerwrapsm_stack. - [x]
removeWidget()removesoldStubfrom layout management and hides it, but leavesm_stackas itsQObjectparent in heap memory. - [ ]
removeWidget()setsm_stack's current index to-1untiloldStub's destructor runs. - [ ] Without
delete oldStub,insertWidget()shiftsrealPagetoidx + 2at the next repaint.
Answer: removeWidget() removes oldStub from layout management and hides it, but leaves m_stack as its QObject parent in heap memory.
Why: QLayout / QStackedWidget removal detaches geometry management without destroying the child QWidget or clearing its QObject::parent().
Common misconception: Assuming removeWidget() deletes the removed widget.
? check 2 · Why should telemetry QLabel controls displaying live serial or CAN strings call setTextFormat(Qt::PlainText)?
- [x] Default
Qt::AutoTextinspects strings for<...>tags and invokes an HTML parser that mangles bracketed tokens like<ERR>. - [ ]
Qt::PlainTextmoves glyph rasterization off the GUI thread onto a kernelDMAchannel. - [ ]
Qt::AutoTexttruncates UTF-8 strings at64characters insideQBoxLayout. - [ ]
QLabelrefuses to participate inQSizePolicy::ExpandingunlessQt::PlainTextis active.
Answer: Default Qt::AutoText inspects strings for <...> tags and invokes an HTML parser that mangles bracketed tokens like <ERR>.
Why: 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.
? check 3 · When is QGraphicsView + QGraphicsScene strongly preferred over nested QGridLayout widgets?
- [ ] Whenever a dialog needs two-column
(Label, QSpinBox)calibration parameter rows. - [ ] Whenever
QScrollAreawraps a vertical stack of fiveQGroupBoxsettings sections. - [ ] Whenever mutually exclusive
QRadioButtoncontrols must report an integer mode ID. - [x] When rendering, panning, zooming, and hit-testing hundreds or thousands of 2D schematic items in world coordinates.
Answer: When rendering, panning, zooming, and hit-testing hundreds or thousands of 2D schematic items in world coordinates.
Why: 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.
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.
Step sequence — frame strip: steps_m05_l01
Populate off-screen QStackedWidget indices with empty QWidget stubs so cold boot builds only page 0.
reveals: step1
highlights: step1
Materialize the target page on first visit and explicitly delete the detached placeholder QWidget.
reveals: step2
highlights: step2
Always call setWidgetResizable(true) after QScrollArea::setWidget() so inner responsive layouts expand.
reveals: step3
highlights: step3
Pin telemetry QLabel instances to Qt::PlainText and reserve QGraphicsView for 2D coordinate scenes.
reveals: step4
highlights: step4
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.
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, QTableWidget, QTreeWidget) and true Model/View views (QListView, QTableView, QTreeView). Item-widgets embed a hidden internal model populated by heap-allocated QListWidgetItem, QTableWidgetItem, or QTreeWidgetItem objects—convenient for a 12-row baud-rate picker, disastrous for telemetry!
Do the arithmetic for a 50,000-row x 4-column industrial fault log: QTableWidget executes 200,000 separate new QTableWidgetItem allocations, converts 200,000 integers and strings into QVariant wrappers upfront, consumes tens of megabytes of fragmented heap, and freezes the GUI thread for over 100 ms.
With QTableView + QAbstractTableModel (or QListView + QAbstractListModel), your C++ data stays once inside std::vector<TelemetryRecord> (24 bytes * 50,000 = 1.2 MiB contiguous RAM). The view queries rowCount() to scale its scrollbar and calls data(index, role) ONLY for the ~25 rows visible on screen!
Figure 5.2a. Memory layout and GUI-thread latency comparison at 50,000 rows x 4 columns.
mental model: 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.
definition ( & Qt::): 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.
- Step 1. Avoid 200,000 individual heap item allocations by backing views directly with a contiguous std::vector<Record>.
- Step 2. Return 0 in rowCount(parent) and columnCount(parent) whenever parent.isValid() is true on flat models.
- Step 3. Expose typed UserRole integers for logic/sorting and return empty QVariant{} on unhandled roles.
- Step 4. Set uniformItemSizes / fixed vertical row heights so views compute 50,000-row scrollbars in O(1) time.
Figure 5.2b. Store records in std::vector<T>, serve visible cells via data(), and return {} else.
QModelIndex Lifetimes, Qt::ItemDataRole Facets, and Tree vs Flat Contracts
QModelIndex is a tiny stack value (row(), column(), internalPointer(), model()), never a long-lived handle. As soon as a row is inserted or evicted ahead of row k, any saved QModelIndex for row k points to the wrong record or out-of-bounds memory—never store QModelIndex as a class member!
Inside data(const QModelIndex &idx, int role), Qt::ItemDataRole cleanly separates presentation from typed domain values. One TelemetryRecord answers Qt::DisplayRole with formatted units ("418 kPa"), Qt::ForegroundRole with alarm crimson (#DC2626), Qt::TextAlignmentRole with right alignment, and Qt::UserRole + 1 with the raw int 418 so filter proxies never scanf formatted UI strings! Always return QVariant{} for unhandled roles—returning a string when Qt queries Qt::CheckStateRole renders an accidental checkbox inside every single cell!
Finally, note how QTreeView generalizes tables and lists: every model method receives const QModelIndex &parent. In a hierarchical QAbstractItemModel (such as a CANopen object-dictionary tree), index(r, c, parent) and parent(child) walk node pointers via createIndex(r, c, nodePtr). In a flat QAbstractTableModel, cells have NO child rows, so rowCount(parent) and columnCount(parent) must return 0 whenever parent.isValid()!
Figure 5.2b. Mapping QListView, QTableView, and QTreeView onto QAbstractItemModel virtual contracts.
| Widget / View Class | Backing Storage | 50,000-Row Heap Cost | Mandatory Performance / Correctness Rule |
|---|---|---|---|
QTableWidget / QListWidget | O(R*C) heap *WidgetItems | 200,000 heap objects (>15 MiB) | Restrict strictly to small static tables (< 200 rows) |
QTableView + QAbstractTableModel | Flat std::vector<Struct> | 0 item objects (1.2 MiB vector) | Return 0 if parent.isValid(); lock verticalHeader default height |
QListView + QAbstractListModel | Flat std::vector<Struct> / ring | 0 item objects | Call setUniformItemSizes(true) for O(1) scrollbar layout |
QTreeView + QAbstractItemModel | Node arena / tree pointers | 0 QTreeWidgetItem wrappers | Implement exact index() / parent() inverse via createIndex() |
learner@ksa:~/gl-q01/m05-l02$ bat -H 30 -H 66 telemetry_table_model.hpp File: telemetry_table_model.hpp #pragma once #include <QAbstractTableModel> #include <QColor> #include <QHeaderView> #include <QListView> #include <QString> #include <QTableView> #include <QVariant> #include <cstdint> #include <vector> struct TelemetrySample { std::uint64_t timestampMs; std::uint16_t channelId; std::int32_t valueKpa; std::uint8_t severity; // 0=Normal, 1=Warn, 2=Critical }; class TelemetryTableModel final : public QAbstractTableModel { Q_OBJECT public: enum CustomRoles : int { RawValueRole = Qt::UserRole + 1, SeverityRole = Qt::UserRole + 2, }; explicit TelemetryTableModel(QObject *parent = nullptr) : QAbstractTableModel(parent) {} int rowCount(const QModelIndex &parent = QModelIndex()) const override { return parent.isValid() ? 0 : static_cast<int>(m_rows.size()); } int columnCount(const QModelIndex &parent = QModelIndex()) const override { return parent.isValid() ? 0 : 4; } QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override { if (orientation != Qt::Horizontal || role != Qt::DisplayRole) return {}; switch (section) { case 0: return tr("Timestamp (ms)"); case 1: return tr("Channel"); case 2: return tr("Pressure"); case 3: return tr("Severity"); default: return {}; } } QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override { if (!idx.isValid() || idx.row() < 0 || idx.row() >= static_cast<int>(m_rows.size())) { return {}; } const auto &s = m_rows[static_cast<std::size_t>(idx.row())]; if (role == RawValueRole) return s.valueKpa; if (role == SeverityRole) return static_cast<int>(s.severity); if (role == Qt::ForegroundRole && s.severity >= 2) { return QColor(0xDC, 0x26, 0x26); } if (role == Qt::TextAlignmentRole && idx.column() != 3) { return int(Qt::AlignRight | Qt::AlignVCenter); } if (role != Qt::DisplayRole) { return {}; // Mandatory: keeps CheckStateRole / DecorationRole empty! } switch (idx.column()) { case 0: return QVariant::fromValue(s.timestampMs); case 1: return QStringLiteral("CH-%1").arg(s.channelId, 2, 10, QLatin1Char('0')); case 2: return QStringLiteral("%1 kPa").arg(s.valueKpa); case 3: return s.severity >= 2 ? tr("CRITICAL") : (s.severity == 1 ? tr("WARN") : tr("OK")); default: return {}; } } static void tuneHighRateViews(QTableView *table, QListView *list) { table->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); table->verticalHeader()->setDefaultSectionSize(28); list->setUniformItemSizes(true); // O(1) scrollbar geometry at 50,000 rows! } private: std::vector<TelemetrySample> m_rows; };- Returning 0 when parent.isValid() tells views that flat table cells do not own nested tree children.
- Returning empty QVariant{} for non-DisplayRole queries prevents accidental checkboxes on CheckStateRole.
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 Lesson 5.2 QAbstractTableModel-Roles(3qt) GL-Q01 quick reference · full manual page: man 3qt QAbstractTableModel-Roles Host C++20 Benchmark Contrasting 50,000-Row Virtual Models vs Item Allocation
In verify.cpp, we populate 50,000 contiguous SampleRow structs (16 bytes each = 800 KiB) and measure CLOCK_MONOTONIC latency of 100-cell (25 x 4) viewport queries in the middle of the dataset (rows 25,000..25,024), comparing against eager 200,000-cell HeapWidgetCell construction.
Simultaneously, assertions verify row_count(valid_parent = true) == 0, !data(CheckState).valid, and typed UserSeverity / UserValue integer extraction without string parsing.
learner@ksa:~/gl-q01/m05-l02$ bat -H 35 -H 48 verify.cpp File: verify.cpp #include <algorithm> #include <array> #include <cassert> #include <cstdint> #include <cstdio> #include <ctime> #include <memory> #include <string> #include <vector> enum class Role { Display, Foreground, CheckState, UserValue, UserSeverity }; struct Variant { bool valid = false; std::int64_t num = 0; std::string str; }; struct Index { int row = -1; int col = -1; constexpr bool is_valid() const noexcept { return row >= 0 && col >= 0; } }; struct SampleRow { std::uint64_t ts_ms; std::int32_t kpa; std::uint16_t ch; std::uint8_t sev; }; class VirtualTelemetryModel { public: explicit VirtualTelemetryModel(std::vector<SampleRow> rows) noexcept : m_rows(std::move(rows)) {} int row_count(Index parent = {}) const noexcept { return parent.is_valid() ? 0 : static_cast<int>(m_rows.size()); } int col_count(Index parent = {}) const noexcept { return parent.is_valid() ? 0 : 4; } Variant data(Index idx, Role role) const { if (!idx.is_valid() || idx.row >= row_count() || idx.col >= col_count()) { return {}; } const auto &r = m_rows[static_cast<std::size_t>(idx.row)]; if (role == Role::UserValue) return {true, r.kpa, {}}; if (role == Role::UserSeverity) return {true, r.sev, {}}; if (role == Role::Foreground && r.sev >= 2) return {true, 0xDC2626, {}}; if (role != Role::Display) return {}; // CheckState stays invalid! switch (idx.col) { case 0: return {true, static_cast<std::int64_t>(r.ts_ms), std::to_string(r.ts_ms)}; case 1: return {true, r.ch, "CH-" + std::to_string(r.ch)}; case 2: return {true, r.kpa, std::to_string(r.kpa) + " kPa"}; case 3: return {true, r.sev, r.sev >= 2 ? "CRITICAL" : "OK"}; default: return {}; } } private: std::vector<SampleRow> m_rows; }; struct HeapWidgetCell { std::string text; std::uint32_t fg = 0; }; static std::uint64_t mono_ns() noexcept { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } int main() { constexpr std::size_t kRows = 50000; std::vector<SampleRow> backing(kRows); for (std::size_t i = 0; i < kRows; ++i) { backing[i] = {10000ULL + i, static_cast<std::int32_t>(150 + (i % 320)), static_cast<std::uint16_t>(i % 8), static_cast<std::uint8_t>(i % 3)}; } // Measure eager O(R*C) item-widget build on 5,000 rows (scaled 10x conservative bound) const std::uint64_t t_eager0 = mono_ns(); std::vector<std::unique_ptr<HeapWidgetCell>> eager_cells; eager_cells.reserve(5000U * 4U); for (std::size_t r = 0; r < 5000U; ++r) { for (int c = 0; c < 4; ++c) { eager_cells.push_back(std::make_unique<HeapWidgetCell>( HeapWidgetCell{std::to_string(backing[r].kpa), 0U})); } } const std::uint64_t eager_5k_ns = mono_ns() - t_eager0; VirtualTelemetryModel model(std::move(backing)); assert(model.row_count() == 50000 && model.row_count({0, 0}) == 0); assert(!model.data({0, 0}, Role::CheckState).valid); assert(model.data({2, 0}, Role::UserSeverity).num == 2); assert(model.data({2, 3}, Role::Display).str == "CRITICAL"); std::array<std::uint64_t, 31> vp_ns{}; std::size_t sink = 0; for (std::size_t pass = 0; pass < vp_ns.size(); ++pass) { const std::uint64_t t0 = mono_ns(); for (int r = 25000; r < 25025; ++r) { for (int c = 0; c < 4; ++c) { sink += model.data({r, c}, Role::Display).str.size(); } } vp_ns[pass] = mono_ns() - t0; } std::sort(vp_ns.begin(), vp_ns.end()); assert(sink > 0 && eager_cells.size() == 20000U); std::printf("model_audit: rows=%d item_allocs=0 vp25_p50_ns=%llu eager5k_alloc_ns=%llu\n", model.row_count(), static_cast<unsigned long long>(vp_ns[15]), static_cast<unsigned long long>(eager_5k_ns)); return 0; }- Flat table model returns 0 when parent.is_valid() is true, matching QAbstractTableModel's leaf contract.
- Non-Display queries fall through to empty Variant{}, preventing CheckStateRole phantom checkboxes.
Comparing O(visible) Viewport Latency Against Eager Item Allocation
Inspect the ./verify output: rows=50000 item_allocs=0 renders a 25-row (100-cell) viewport straight out of the middle of 50,000 records in single-digit microseconds (vp25_p50_ns), whereas allocating even one-tenth (5,000 x 4 = 20,000) of an item-widget grid costs orders of magnitude more heap time (eager5k_alloc_ns).
Next, Lesson 5.3 solves live mutation: appending new telemetry, evicting oldest ring entries, sorting and filtering via QSortFilterProxyModel, undoing edits via QUndoStack, and custom-painting badges without ever resetting the user's scroll bar.
learner@ksa:~/gl-q01/m05-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m05-l02./verifymodel_audit: rows=50000 item_allocs=0 vp25_p50_ns=15989 eager5k_alloc_ns=5646864learner@ksa:~/gl-q01/m05-l02learner@ksa:~/gl-q01/m05-l02strace -e trace=write,exit_group ./verifywrite(1, "model_audit: rows=50000 item_all"..., 81) = 81exit_group(0) = ?+++ exited with 0 +++Classic Custom Model Bugs: Phantom Checkboxes and ResizeToContents Freezes
Separating contiguous C++ backing storage from transient QModelIndex role queries scales QTableView, QListView, and QTreeView to tens of thousands of industrial records on modest embedded CPUs.
Keep host-versus-target measurements scoped accurately: host CLOCK_MONOTONIC timings measure pure C++20 data() formatting in DRAM, whereas target scroll smoothness on Cortex-A7 also includes QFontEngine glyph cache blits inside QStyledItemDelegate.
Returning Text Without Checking if (role == Qt::DisplayRole) in data():
- 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.
Enabling QHeaderView::ResizeToContents on a 50,000-Row QTableView:
- 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.
Guided Practice
Extend VirtualTelemetryModel in verify.cpp with a header_data(int section, Role role) method that returns column titles ONLY when role == Role::Display and returns an invalid Variant{} for Role::CheckState, asserting that all 4 horizontal headers report non-empty titles and empty check states.
Independent Practice
Implement a two-level hierarchical DeviceTreeModel in ISO C++20 (parent() and index() using integer node indices 0..N-1 stored in an arena std::vector<Node>) representing 3 I2C buses with 4 sensor child nodes each, proving row_count(root) == 3, row_count(bus_i) == 4, and row_count(sensor) == 0.
Verification Checks
? check 1 · Every cell in a custom QAbstractTableModel unexpectedly draws a checkbox beside its text even though Qt::ItemIsUserCheckable was never set. Why?
- [x]
data()returned a non-emptyQVariantwithout checkingrole == Qt::DisplayRole, answeringQt::CheckStateRole. - [ ]
QTableViewdraws checkboxes on all columns unlesssetUniformItemSizes(true)is called. - [ ]
rowCount()returned a nonzero count whenparent.isValid()wastrue. - [ ]
headerData()returnedQt::Horizontalstrings forQt::Verticalrow headers.
Answer: data() returned a non-empty QVariant without checking role == Qt::DisplayRole, answering Qt::CheckStateRole.
Why: 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().
? check 2 · Why must a flat QAbstractTableModel::rowCount(const QModelIndex &parent) return 0 whenever parent.isValid() is true?
- [ ]
parent.isValid()istrueonly while the model is empty or mid-destruction. - [ ] Returning
m_rows.size()causesQSortFilterProxyModelto deletem_rows. - [ ]
QTableViewpasses a validparentwhenever the vertical scrollbar reaches the bottom. - [x] In a flat table, only the invalid root index owns rows; valid cell indices are leaves with zero child rows.
Answer: In a flat table, only the invalid root index owns rows; valid cell indices are leaves with zero child rows.
Why: 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().
? check 3 · Which pair of view settings prevents O(N) full-model height scans when scrolling 50,000 rows in QListView and QTableView?
- [ ]
listView->setWordWrap(true)andtableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents). - [ ]
listView->blockSignals(true)andtableView->setIndexWidget()on every row. - [x]
listView->setUniformItemSizes(true)andtableView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed). - [ ]
listView->setAutoRepeat(false)andtableView->resizeRowsToContents().
Answer: listView->setUniformItemSizes(true) and tableView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed).
Why: 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.
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).
Step sequence — frame strip: steps_m05_l02
Avoid 200,000 individual heap item allocations by backing views directly with a contiguous std::vector<Record>.
reveals: step1
highlights: step1
Return 0 in rowCount(parent) and columnCount(parent) whenever parent.isValid() is true on flat models.
reveals: step2
highlights: step2
Expose typed UserRole integers for logic/sorting and return empty QVariant{} on unhandled roles.
reveals: step3
highlights: step3
Set uniformItemSizes / fixed vertical row heights so views compute 50,000-row scrollbars in O(1) time.
reveals: step4
highlights: step4
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.
Structural Notification Contracts vs the beginResetModel Anti-Pattern
When live telemetry appends to m_rows at 20 Hz, calling beginResetModel(); endResetModel(); tells every attached QTableView and QSortFilterProxyModel that the entire universe was destroyed: operator row selection vanishes, open context menus close, and scrollbars snap violently! Granular notifications—beginInsertRows, endInsertRows, beginRemoveRows, endRemoveRows, and dataChanged—update QPersistentModelIndex trackers incrementally so selection glides smoothly as rows enter and leave.
Two invariants in QAbstractItemModel are non-negotiable. First, beginInsertRows(parent, first, last) and beginRemoveRows(parent, first, last) MUST execute BEFORE m_rows changes size, and end*Rows() executes immediately AFTER. Second, [first, last] is an INCLUSIVE index range: appending 1 item onto a 5-element vector (indices 0..4) calls beginInsertRows(QModelIndex(), 5, 5), never (5, 6)!
For non-structural edits—such as toggling an acknowledged flag on row r—do not touch insert/remove signals at all; mutate the struct field and emit dataChanged(index(r, 0), index(r, 3), {Qt::DisplayRole, Qt::ForegroundRole}).
Figure 5.3a. Preserving selection, scroll position, and 60 Hz frame budgets on live filtered tables.
mental model: 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.
definition (beginInsertRows Bracket & ): 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.
- Step 1. Call beginInsertRows with inclusive [first, last] bounds BEFORE mutating m_rows, then call endInsertRows.
- Step 2. Always translate view click or selection indices through proxy->mapToSource(proxyIndex) before reading m_rows.
- Step 3. Route operator parameter and table edits through QUndoStack so mis-clicks reverse deterministically.
- Step 4. Use one shared QStyledItemDelegate with painter->save()/restore() instead of calling setIndexWidget() per row.
Figure 5.3b. Call beginInsertRows(p,N,N) before push_back, mapToSource on clicks, and use delegates.
QSortFilterProxyModel Coordinate Mapping, QUndoStack, and Flyweight Delegates
QSortFilterProxyModel wraps a source model to filter rows (filterAcceptsRow) and sort columns without copying a single TelemetrySample struct. In Qt 6.8, mutating filter parameters calls beginFilterChange() before updating the member threshold and endFilterChange(QSortFilterProxyModel::Direction::Rows) after. Crucially, QTableView signals emit PROXY QModelIndex coordinates—always translate via const QModelIndex srcIdx = proxy->mapToSource(proxyIdx); before indexing your source model!
When operators acknowledge alarms or tune calibration cells inside a table, wrapping mutations in QUndoCommand subclasses pushed onto a QUndoStack (undoStack->push(cmd) executes cmd->redo() immediately!) gives one-line Ctrl+Z / Ctrl+Y safety and free visual audit history via QUndoView.
Finally, resist calling tableView->setIndexWidget(idx, new QPushButton(...)) on large tables: 5,000 embedded widgets re-introduce the exact heap and layout freeze we eliminated in Lesson 5.2! Subclass QStyledItemDelegate::paint(QPainter *p, const QStyleOptionViewItem &opt, const QModelIndex &idx) once, bracket custom drawing in p->save() / p->restore(), and render 25 visible severity pills at zero widget cost.
Figure 5.3b. Exact coordinate rules across QAbstractItemModel notifications, proxies, QUndoStack, and delegates.
| Model / View Operation | Correct Qt 6.8 Mechanism | Broken Anti-Pattern | Failure Symptom of Anti-Pattern |
|---|---|---|---|
Append 1 row at N = m_rows.size() | beginInsertRows({}, N, N) -> push_back -> endInsertRows() | push_back before beginInsertRows({}, N, N+1) | Off-by-one proxy crash or corrupted row count |
Update 1 field in row r | Mutate field + emit dataChanged(tl, br, {roles}) | beginResetModel() + endResetModel() | Wipes user selection, focus, and scroll position |
Handle click on filtered QTableView | proxy->mapToSource(proxyIdx).row() | sourceModel->at(proxyIdx.row()) | Acknowledges or deletes the WRONG backing record! |
| Render custom severity pill per row | Single QStyledItemDelegate::paint (save/restore) | view->setIndexWidget() per row | Thousands of child QWidget allocations stall scrolling |
learner@ksa:~/gl-q01/m05-l03$ bat -H 37 -H 74 proxy_delegate_undo.cpp File: proxy_delegate_undo.cpp #include <QAbstractTableModel> #include <QPainter> #include <QSortFilterProxyModel> #include <QStyledItemDelegate> #include <QUndoCommand> #include <QUndoStack> #include <vector> struct AlarmEntry { int id; int severity; // 0=Info, 1=Warn, 2=Critical bool acked = false; }; class LiveAlarmModel final : public QAbstractTableModel { Q_OBJECT public: enum Roles : int { SeverityRole = Qt::UserRole + 1 }; explicit LiveAlarmModel(QObject *parent = nullptr) : QAbstractTableModel(parent) {} int rowCount(const QModelIndex &p = {}) const override { return p.isValid() ? 0 : static_cast<int>(m_rows.size()); } int columnCount(const QModelIndex &p = {}) const override { return p.isValid() ? 0 : 2; } QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override { if (!idx.isValid() || idx.row() >= static_cast<int>(m_rows.size())) return {}; const auto &a = m_rows[static_cast<std::size_t>(idx.row())]; if (role == SeverityRole) return a.severity; if (role != Qt::DisplayRole) return {}; return idx.column() == 0 ? QString::number(a.id) : (a.acked ? tr("ACKED") : tr("ACTIVE")); } void appendAlarm(AlarmEntry entry) { const int n = static_cast<int>(m_rows.size()); beginInsertRows(QModelIndex(), n, n); // Inclusive [n, n] BEFORE push_back! m_rows.push_back(entry); endInsertRows(); } void setAcked(int sourceRow, bool acked) { if (sourceRow < 0 || sourceRow >= static_cast<int>(m_rows.size())) return; m_rows[static_cast<std::size_t>(sourceRow)].acked = acked; const QModelIndex c = index(sourceRow, 1); emit dataChanged(c, c, {Qt::DisplayRole}); } bool isAcked(int sourceRow) const { return m_rows.at(static_cast<std::size_t>(sourceRow)).acked; } private: std::vector<AlarmEntry> m_rows; }; class AckAlarmCommand final : public QUndoCommand { public: AckAlarmCommand(LiveAlarmModel *model, int srcRow, QUndoCommand *parent = nullptr) : QUndoCommand(QObject::tr("Acknowledge Alarm"), parent), m_model(model), m_row(srcRow), m_prev(model->isAcked(srcRow)) {} void redo() override { m_model->setAcked(m_row, true); } void undo() override { m_model->setAcked(m_row, m_prev); } private: LiveAlarmModel *m_model; int m_row; bool m_prev; }; class SeverityProxy final : public QSortFilterProxyModel { Q_OBJECT public: explicit SeverityProxy(QObject *parent = nullptr) : QSortFilterProxyModel(parent) {} void setMinSeverity(int sev) { if (m_min == sev) return; beginFilterChange(); // Qt 6.8 directional filter update m_min = sev; endFilterChange(QSortFilterProxyModel::Direction::Rows); } protected: bool filterAcceptsRow(int srcRow, const QModelIndex &srcParent) const override { const QModelIndex idx = sourceModel()->index(srcRow, 0, srcParent); return idx.data(LiveAlarmModel::SeverityRole).toInt() >= m_min; } private: int m_min = 0; }; class PillBadgeDelegate final : public QStyledItemDelegate { Q_OBJECT public: using QStyledItemDelegate::QStyledItemDelegate; void paint(QPainter *p, const QStyleOptionViewItem &opt, const QModelIndex &idx) const override { if (idx.data(LiveAlarmModel::SeverityRole).toInt() < 2) { QStyledItemDelegate::paint(p, opt, idx); return; } p->save(); // Borrowed QPainter: always restore state! p->setRenderHint(QPainter::Antialiasing, true); const QRect r = opt.rect.adjusted(4, 3, -4, -3); p->setPen(Qt::NoPen); p->setBrush(QColor(0xB9, 0x1C, 0x1C)); p->drawRoundedRect(r, 4.0, 4.0); p->setPen(QColor(0xF8, 0xFA, 0xFC)); p->drawText(r, Qt::AlignCenter, idx.data().toString()); p->restore(); } };- beginInsertRows((), n, n) runs BEFORE m_rows.push_back with inclusive [n, n] bounds.
- Qt 6.8 beginFilterChange() + endFilterChange(Direction::Rows) refreshes row filtering cleanly.
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 Lesson 5.3 QSortFilterProxyModel-QUndoStack(3qt) GL-Q01 quick reference · full manual page: man 3qt QSortFilterProxyModel-QUndoStack Host C++20 Verifier for Persistent Selection, Proxy Mapping, and Undo/Redo
In verify.cpp, we verify all three dynamic Model/View contracts together: PersistentIndex row shifting across prepend insertions and deletions, FilterSortProxy map_to_source() translation, and UndoStack push / undo / redo acknowledgement state transitions.
Trace the sequence carefully: selecting row 1 (id = 102), prepending urgent id = 100 at row 0 shifts the persistent handle to row 2 (still id = 102), acknowledging via proxy.map_to_source(1) targets id = 102 accurately, and undo() / redo() toggles acked cleanly.
learner@ksa:~/gl-q01/m05-l03$ bat -H 20 -H 57 verify.cpp File: verify.cpp #include <cassert> #include <cstdio> #include <memory> #include <vector> struct Alarm { int id; int sev; bool acked = false; }; class LiveStore { public: int track_persistent(int row) { m_pers.push_back(row); return static_cast<int>(m_pers.size() - 1U); } int persistent_row(int h) const noexcept { return m_pers[static_cast<std::size_t>(h)]; } void insert_row(int pos, Alarm a) { assert(pos >= 0 && pos <= static_cast<int>(m_rows.size())); m_rows.insert(m_rows.begin() + pos, a); for (int &r : m_pers) { if (r >= pos) ++r; } } void remove_row(int pos) { assert(pos >= 0 && pos < static_cast<int>(m_rows.size())); m_rows.erase(m_rows.begin() + pos); for (int &r : m_pers) { if (r == pos) r = -1; else if (r > pos) --r; } } void set_acked(int row, bool v) { m_rows.at(static_cast<std::size_t>(row)).acked = v; } const Alarm &at(int row) const { return m_rows.at(static_cast<std::size_t>(row)); } int count() const noexcept { return static_cast<int>(m_rows.size()); } private: std::vector<Alarm> m_rows; std::vector<int> m_pers; }; class ProxyMap { public: explicit ProxyMap(const LiveStore &src) noexcept : m_src(src) {} void set_min_sev(int sev) { m_min = sev; rebuild(); } void rebuild() { m_map.clear(); for (int r = 0; r < m_src.count(); ++r) { if (m_src.at(r).sev >= m_min) m_map.push_back(r); } } int row_count() const noexcept { return static_cast<int>(m_map.size()); } int map_to_source(int p_row) const noexcept { return (p_row >= 0 && p_row < row_count()) ? m_map[static_cast<std::size_t>(p_row)] : -1; } private: const LiveStore &m_src; int m_min = 0; std::vector<int> m_map; }; class UndoAckStack { public: void push_ack(LiveStore &store, int src_row) { const bool prev = store.at(src_row).acked; store.set_acked(src_row, true); m_cmds.resize(m_idx); m_cmds.push_back({src_row, prev}); ++m_idx; } void undo(LiveStore &store) { assert(m_idx > 0); --m_idx; store.set_acked(m_cmds[m_idx].row, m_cmds[m_idx].prev); } void redo(LiveStore &store) { assert(m_idx < m_cmds.size()); store.set_acked(m_cmds[m_idx].row, true); ++m_idx; } private: struct Cmd { int row; bool prev; }; std::vector<Cmd> m_cmds; std::size_t m_idx = 0; }; int main() { LiveStore store; store.insert_row(0, {101, 0, false}); store.insert_row(1, {102, 2, false}); store.insert_row(2, {103, 1, false}); const int h_sel = store.track_persistent(1); // id=102 store.insert_row(0, {100, 2, false}); // prepend -> sel shifts 1 -> 2 assert(store.persistent_row(h_sel) == 2 && store.at(2).id == 102); ProxyMap proxy(store); proxy.set_min_sev(2); // Keeps src rows 0 (id=100) and 2 (id=102) assert(proxy.row_count() == 2); const int clicked_src = proxy.map_to_source(1); assert(clicked_src == 2 && store.at(clicked_src).id == 102); UndoAckStack undo; undo.push_ack(store, clicked_src); assert(store.at(2).acked); undo.undo(store); assert(!store.at(2).acked); undo.redo(store); assert(store.at(2).acked); store.remove_row(2); // Evict selected row -> handle becomes -1 assert(store.persistent_row(h_sel) == -1); std::printf("proxy_undo_audit: crit_rows=%d mapped_src=%d redo_acked=1 evicted_handle=%d\n", proxy.row_count(), clicked_src, store.persistent_row(h_sel)); return 0; }- Inserting at pos shifts all persistent indices >= pos upward by +1 so operator selection stays locked on id=102.
- map_to_source(1) translates filtered proxy row 1 into backing source row 2 before UndoAckStack mutates store.
Verifying Persistent Shifts, Proxy Coordinate Mapping, and Undo History
Confirm ./verify outputs proxy_undo_audit: crit_rows=2 mapped_src=2 redo_acked=1 evicted_handle=-1. Without map_to_source(1), indexing store.at(1) directly would have acknowledged id = 101 (Info) instead of id = 102 (Critical)!
Now put the complete bounded ring-buffer model, persistent selection shifter, and sort/filter proxy through lab_m05_table_model_roles.
learner@ksa:~/gl-q01/m05-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m05-l03./verifyproxy_undo_audit: crit_rows=2 mapped_src=2 redo_acked=1 evicted_handle=-1learner@ksa:~/gl-q01/m05-l03learner@ksa:~/gl-q01/m05-l03strace -e trace=write,exit_group ./verifywrite(1, "proxy_undo_audit: crit_rows=2 ma"..., 74) = 74exit_group(0) = ?+++ exited with 0 +++Proxy Row Mix-Ups, Painter State Leaks, and Half-Open Insert Bounds
Granular beginInsertRows/beginRemoveRows brackets, zero-copy QSortFilterProxyModel views, QUndoStack commands, and flyweight QStyledItemDelegate rendering form the gold-standard Qt 6 data-grid architecture.
In Module 6, we complete GL-Q01 with crash-atomic QSaveFile configuration persistence, premultiplied ARGB32 QPainter gauges, ring-buffered QtCharts, and headless QTest TAP 13 suites.
Passing Proxy QModelIndex Rows Directly to the Source Model:
- 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.
Mutating Shared QPainter Pens or Clips Inside QStyledItemDelegate::paint Without restore():
- 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.
Guided Practice
Extend ProxyMap in verify.cpp with map_from_source(int src_row) returning the proxy row index (or -1 if filtered out), and assert that map_from_source(1) (id = 101, sev = 0) returns -1 while map_from_source(2) (id = 102, sev = 2) returns 1.
Independent Practice
Complete lab_m05_table_model_roles by fixing the three defects in starter/core.cpp: returning empty RoleValue{} for DataRole::CheckState, decrementing surviving persistent row handles when FIFO capacity evicts row 0, and translating FaultFilterProxy::data through map_to_source(proxy_row).
Verification Checks
? check 1 · m_rows currently holds 6 elements (indices 0..5). Which exact sequence validly appends 1 new record to a QAbstractTableModel?
- [ ]
m_rows.push_back(rec); beginInsertRows(QModelIndex(), 6, 7); endInsertRows(); - [ ]
beginInsertRows(QModelIndex(), 5, 6); m_rows.push_back(rec); endInsertRows(); - [ ]
beginInsertRows(index(6, 0), 0, 0); m_rows.push_back(rec); endResetModel(); - [x]
beginInsertRows(QModelIndex(), 6, 6); m_rows.push_back(rec); endInsertRows();
Answer: beginInsertRows(QModelIndex(), 6, 6); m_rows.push_back(rec); endInsertRows();
Why: 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.
? check 2 · A QTableView is attached to SeverityProxy *proxy wrapping LiveAlarmModel *src. Inside connect(view, &QTableView::doubleClicked, ...), how do you locate the clicked AlarmEntry?
- [ ] Call
proxy->invalidate()first soproxyIdx.row()mutates in place to equal the source row. - [ ] Cast
proxyIdx.internalPointer()directly toconst AlarmEntry *. - [x] Translate
const QModelIndex srcIdx = proxy->mapToSource(proxyIdx);and indexsrcwithsrcIdx.row(). - [ ] Index
src->at(proxyIdx.row())directly becauseQTableViewunwraps proxy indices before emitting signals.
Answer: Translate const QModelIndex srcIdx = proxy->mapToSource(proxyIdx); and index src with srcIdx.row().
Why: 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().
? check 3 · Why is QStyledItemDelegate::paint vastly more scalable than QTableView::setIndexWidget() for rendering status pills in a 10,000-row table?
- [ ]
setIndexWidget()deletesQUndoStackcommands whenever the user scrolls vertically. - [x] One flyweight
QStyledItemDelegatepaints only the~25visible cells per frame with zero per-rowQWidgetheap or layout overhead. - [ ]
setIndexWidget()refuses to render insideQTableViewwhenever aQSortFilterProxyModelis attached. - [ ]
QStyledItemDelegatepre-compilesQPainterstrokes intoLinux kerneleBPFbytecode.
Answer: One flyweight QStyledItemDelegate paints only the ~25 visible cells per frame with zero per-row QWidget heap or layout overhead.
Why: 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().
1. Motivation
Implement and verify a bounded-capacity FaultTableModel and FaultFilterProxy with multi-role data() dispatch, FIFO persistent-selection tracking, and map_to_source coordinate translation.
2. Learning objectives
- Guard flat
row_count/column_countagainst valid parents and return emptyRoleValue{}on unhandledCheckStatequeries. - Maintain
QPersistentModelIndex-equivalent selection handles across FIFO capacity eviction and in-place alarm acknowledgement. - Filter and sort alarms zero-copy via
UserSeveritywhile translating proxy rows accurately withmap_to_source.
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7operator console (512 MiBDDR3) runningLinux kernel6.12 LTS and Qt 6.8QTableView+QSortFilterProxyModelover liveSocketCANfault telemetry.
5. Complete executable commands
learner@ksa:~/gl-q01/m05-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/m05-l03$ bat example.cpp File: example.cpp void FaultTableModel::append_fault(FaultItem item) { if (m_rows.size() == m_capacity) { m_rows.erase(m_rows.begin()); for (int &r : m_persistent) { if (r == 0) r = -1; // Evicted row becomes invalid else if (r > 0) --r; // Surviving selections shift -1 } } m_rows.push_back(std::move(item)); } RoleValue FaultFilterProxy::data(int proxy_row, int col, DataRole role) const { const int src_row = map_to_source(proxy_row); // Never index m_src with raw proxy_row! return (src_row < 0) ? RoleValue{} : m_src.data(src_row, col, role); }starter/core.cpp contains three realistic Model/View bugs: FaultTableModel::data falls through on DataRole::CheckState (causing phantom checkboxes), append_fault forgets --r on surviving persistent selections during FIFO eviction, and FaultFilterProxy::data passes unmapped proxy_row straight to m_src.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/m05-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - enforces flat parent=0 guard, typed UserCode/Foreground roles, and empty unhandled CheckStateRole ok 4 - evicts oldest FIFO row at capacity, shifts persistent selections, and updates ack state in place ok 5 - filters and sorts FaultFilterProxy by UserSeverity and translates proxy data() via map_to_source # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-q01/m05-l03$ bat listing.txt File: listing.txt table_model: rows=1024 crit_proxy_rows=341 top_src=1021 top_code=E132Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
Check 3 verifies row_count(true) == 0, !data(CheckState).valid, and UserCode/Foreground projections. Check 4 overflows a 3-row ring buffer, proving handle h0 invalidates to -1 while h1 (seq_id = 11) shifts cleanly from row 1 to row 0 and clears its crimson Foreground role upon set_acknowledged(0, true). Check 5 configures FaultFilterProxy (min_severity = 1, descending sort) and verifies map_to_source(0) == 4 (E505).
9. Experiment variations
- Near transfer: Add a
CommandUndoStackwrapper aroundFaultTableModel::set_acknowledged(row, acked)supportingacknowledge_all_critical()as one macro command whoseundo()restores only previously unacknowledged rows. - Far transfer: Replace
std::vector::erase(begin())(O(capacity)memmove) with a power-of-two circular index(m_head + logical_row) & maskso50,000-row ring eviction runs inO(1)array writes.
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/m05-l03$ bat listing.txt File: listing.txt bench_proxy_refresh_ns: p50=36641 p95=46302 p99=49863 (sink=1136250)The CLOCK_MONOTONIC benchmark measures host C++20 append_fault + 1,024-row FaultFilterProxy sort/filter rebuild latency (nanoseconds per cycle in host DRAM). On target Cortex-A7 hardware, incremental proxy maintenance via beginInsertRows avoids full std::stable_sort passes on every incoming frame.
11. Troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
| Check 3 fails with phantom checkbox error | Starter code lets DataRole::CheckState fall into the DisplayRole switch | Restore if (role != DataRole::Display) return {}; immediately before switch (col) |
| Check 4 fails with h1=1 instead of h1=0 | FIFO eviction erased row 0 without decrementing persistent handles r > 0 | Decrement --r for every persistent handle with r > 0 when row 0 is erased |
| Check 5 fails with text=E101 instead of E505 | FaultFilterProxy::data indexed m_src with proxy_row (0) instead of map_to_source(0) (4) | Set const int src_row = map_to_source(proxy_row); before querying m_src |
12. Guided questions
- Why does FaultFilterProxy sort using DataRole::UserSeverity integers rather than comparing DataRole::Display strings?
- *Hint 1:* Consider both alphabetical order ('CRITICAL' vs 'INFO' vs 'WARN') and UI translations.
- *Hint 2:* Alphabetical string sort orders 'CRITICAL' < 'INFO' < 'WARN' incorrectly and breaks completely under localization, whereas integer UserSeverity (2 > 1 > 0) is fast and locale-invariant.
- Why did FaultFilterProxy::refresh() choose std::stable_sort instead of std::sort?
- *Hint 1:* Think about ties when multiple alarms share the same severity and timestamp.
- *Hint 2:* std::stable_sort preserves relative arrival order among equal-key elements deterministically across refreshes, preventing tied rows from jittering visually on screen.
13. Independent challenges
Upgrade FaultTableModel from std::vector::erase(begin()) to a true O(1) ring buffer (m_head, m_count) and compare ./files/lab_cli --bench p50 / p99 latencies at capacity = 32,768.
14. Solutions and explanations
Strict DisplayRole gating, pre-eviction persistent-handle shifting, and map_to_source coordinate translation keep bounded live telemetry views fast, accurate, and selection-safe.
Run locally in your terminal and check off each verification milestone.
Not started
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().
Step sequence — frame strip: steps_m05_l03
Call beginInsertRows with inclusive [first, last] bounds BEFORE mutating m_rows, then call endInsertRows.
reveals: step1
highlights: step1
Always translate view click or selection indices through proxy->mapToSource(proxyIndex) before reading m_rows.
reveals: step2
highlights: step2
Route operator parameter and table edits through QUndoStack so mis-clicks reverse deterministically.
reveals: step3
highlights: step3
Use one shared QStyledItemDelegate with painter->save()/restore() instead of calling setIndexWidget() per row.
reveals: step4
highlights: step4
m06/
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.
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.
Why Truncate-in-Place Destroys Embedded Configurations on Power Loss
Field technicians shut down industrial machinery by throwing the main 24 V cabinet disconnect without clicking an OS shutdown menu. When an HMI saves calibration constants via QFile f("calib.json"); f.open(QIODevice::WriteOnly);, Qt passes O_WRONLY | O_CREAT | O_TRUNC to openat() in the Linux kernel. That O_TRUNC flag zeroes the existing file's length to 0 bytes BEFORE your first write() executes!
If power drops two milliseconds later—or if ext4 delayed allocation has not yet flushed dirty page-cache blocks to eMMC flash—the machine reboots to a 0-byte or half-written calib.json and loses its factory sensor tare offsets.
QSaveFile eliminates that window completely. open(QIODevice::WriteOnly) opens a hidden sibling temporary file in the same directory as calib.json (guaranteeing the same filesystem mount so rename() never fails with EXDEV). If an error or early return occurs before commit(), ~QSaveFile() automatically calls cancelWriting() and unlink()s the temporary file, leaving the prior calib.json 100% intact!
Figure 6.1a. Linux kernel VFS syscall comparison between in-place QFile truncation and transactional .
mental model: 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.
definition (QSaveFile Atomic Persistence Transaction): 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().
- Step 1. Open QSaveFile at the target path so the temporary sibling resides on the same filesystem mount.
- Step 2. Serialize UTF-8 QJsonDocument or QTextStream content and abort via cancelWriting() on any short write.
- Step 3. Call QSaveFile::commit() (never close(), which is private) and check its boolean return status.
- Step 4. Parse with QFile(ReadOnly) + QJsonParseError and validate domain limits before applying settings.
Figure 6.1b. Ban QFile::Truncate on configs; write UTF-8 into QSaveFile, check errors, and commit().
QSaveFile::commit Internals, UTF-8 QTextStream, and QJsonDocument Validation
Notice a deliberate compile-time safeguard in QSaveFile: QSaveFile::close() is declared private! If migrating QFile code accidentally calls file.close(), compilation fails immediately so you cannot silently bypass commit(). Calling file.commit() flushes user-space buffers, invokes fsync() on the temporary file descriptor so NAND blocks settle on flash, closes the descriptor, and executes atomic POSIX rename() over the destination filename.
Pair QSaveFile with clean UTF-8 serializers. For structured machine configs, build a QJsonObject with an explicit schema "version" integer and serialize via QJsonDocument(obj).toJson(QJsonDocument::Compact). On startup, read via QFile(QIODevice::ReadOnly), pass &QJsonParseError to QJsonDocument::fromJson, and range-check every parameter into local variables before mutating live controller state.
For human-readable audit exports (CSV or INI), attach QTextStream stream(&saveFile). In Qt 6, QTextStream defaults to QStringConverter::Utf8 out of the box—just remember to call stream.flush() and verify stream.status() == QTextStream::Ok before calling saveFile.commit()!
Figure 6.1b. Pairing Qt 6 I/O devices (QFile for reads, QSaveFile for writes) with UTF-8 serializers.
| Persistence Pattern | Kernel Syscall Sequence | 24 V Power-Cut Outcome | Recommended Role | |
|---|---|---|---|---|
| `QFile(WriteOnly | Truncate)` | openat(O_TRUNC) -> write -> close | 0-byte or half-written corrupt file! | NEVER use for critical config/calibration files |
| `QFile(WriteOnly | Append)` | openat(O_APPEND) -> write | Prior lines intact; tail line may truncate | Append-only diagnostic text logs with line CRCs |
QSaveFile + commit() | openat(.tmp) -> write -> fsync -> rename | Atomic: complete old file OR complete new file | All JSON/INI configs, recipes, and tare tables | |
QSaveFile without commit() | openat(.tmp) -> write -> close -> unlink | Clean rollback: .tmp removed, old file intact | Error recovery and exception-safe abort paths |
learner@ksa:~/gl-q01/m06-l01$ bat -H 33 -H 45 atomic_config_persistence.cpp File: atomic_config_persistence.cpp #include <QFile> #include <QJsonDocument> #include <QJsonObject> #include <QJsonParseError> #include <QSaveFile> #include <QString> #include <QStringConverter> #include <QTextStream> struct CalibrationConfig { int zeroOffsetKpa = 0; int alarmLimitKpa = 420; }; class CalibrationPersistence { public: static bool saveJsonAtomic(const QString &path, const CalibrationConfig &cfg) { if (cfg.alarmLimitKpa <= 0 || cfg.alarmLimitKpa > 1000) return false; QSaveFile file(path); // Opens sibling temp file in same directory if (!file.open(QIODevice::WriteOnly)) return false; QJsonObject root; root[QStringLiteral("schema_version")] = 1; root[QStringLiteral("zero_offset_kpa")] = cfg.zeroOffsetKpa; root[QStringLiteral("alarm_limit_kpa")] = cfg.alarmLimitKpa; const QByteArray utf8 = QJsonDocument(root).toJson(QJsonDocument::Compact); if (file.write(utf8) != utf8.size()) { file.cancelWriting(); // Explicit rollback (also run by ~QSaveFile) return false; } return file.commit(); // fsync(tmp_fd) + atomic POSIX rename()! } static bool exportCsvAuditAtomic(const QString &path, const CalibrationConfig &cfg) { QSaveFile file(path); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return false; QTextStream out(&file); out.setEncoding(QStringConverter::Utf8); out << "parameter,value_kpa " << "zero_offset," << cfg.zeroOffsetKpa << ' ' << "alarm_limit," << cfg.alarmLimitKpa << ' '; out.flush(); if (out.status() != QTextStream::Ok) { file.cancelWriting(); return false; } return file.commit(); } static bool loadJsonValidated(const QString &path, CalibrationConfig &out) { QFile file(path); if (!file.open(QIODevice::ReadOnly)) return false; QJsonParseError err{}; const QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &err); if (err.error != QJsonParseError::NoError || !doc.isObject()) return false; const QJsonObject obj = doc.object(); const int limit = obj.value(QStringLiteral("alarm_limit_kpa")).toInt(-1); if (limit <= 0 || limit > 1000) return false; out.zeroOffsetKpa = obj.value(QStringLiteral("zero_offset_kpa")).toInt(0); out.alarmLimitKpa = limit; return true; } };- QSaveFile::commit() flushes bytes to storage via fsync() and atomically swaps the directory entry via rename().
- Flush QTextStream and verify out.status() == QTextStream::Ok before committing UTF-8 text exports.
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 Lesson 6.1 QSaveFile-QTextStream(3qt) GL-Q01 quick reference · full manual page: man 3qt QSaveFile-QTextStream Host C++20 Verifier Traced Under strace for Atomic Commit and Unlink Rollback
In verify.cpp, we build a POSIX AtomicSaveTransaction matching QSaveFile's exact syscall sequence (openat sibling .tmp, write, fsync, close, rename, and destructor unlink rollback) and trace it live with strace -e trace=openat,write,fsync,rename,renameat,renameat2,unlink,exit_group!
Watch what happens across the two scopes in main(): scope 1 commits v1 (40 bytes) cleanly, while scope 2 writes a truncated corrupt string "{\"corrupt_half" and exits scope WITHOUT calling commit()—triggering destructor unlink so v1 survives byte-for-byte intact!
learner@ksa:~/gl-q01/m06-l01$ bat -H 48 -H 98 verify.cpp File: verify.cpp #include <cassert> #include <cstdio> #include <cstdlib> #include <fcntl.h> #include <string> #include <string_view> #include <unistd.h> class AtomicSaveTransaction { public: explicit AtomicSaveTransaction(std::string target) : m_target(std::move(target)), m_tmp(m_target + ".tmp") {} ~AtomicSaveTransaction() { if (m_active) cancel_writing(); } AtomicSaveTransaction(const AtomicSaveTransaction &) = delete; AtomicSaveTransaction &operator=(const AtomicSaveTransaction &) = delete; bool open_write() noexcept { m_fd = ::openat(AT_FDCWD, m_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); m_active = (m_fd >= 0); return m_active; } bool write_all(std::string_view bytes) noexcept { if (!m_active || m_fd < 0) return false; std::size_t off = 0; while (off < bytes.size()) { const ssize_t n = ::write(m_fd, bytes.data() + off, bytes.size() - off); if (n <= 0) { cancel_writing(); return false; } off += static_cast<std::size_t>(n); } return true; } void cancel_writing() noexcept { if (m_fd >= 0) { ::close(m_fd); m_fd = -1; } if (m_active) { ::unlink(m_tmp.c_str()); m_active = false; } } bool commit() noexcept { if (!m_active || m_fd < 0) return false; if (::fsync(m_fd) != 0) { cancel_writing(); return false; } ::close(m_fd); m_fd = -1; if (::rename(m_tmp.c_str(), m_target.c_str()) != 0) { ::unlink(m_tmp.c_str()); m_active = false; return false; } m_active = false; return true; } private: std::string m_target; std::string m_tmp; int m_fd = -1; bool m_active = false; }; static std::string read_file(const std::string &p) { const int fd = ::openat(AT_FDCWD, p.c_str(), O_RDONLY | O_CLOEXEC); assert(fd >= 0); char buf[256]{}; const ssize_t n = ::read(fd, buf, sizeof(buf) - 1U); ::close(fd); assert(n >= 0); return std::string(buf, static_cast<std::size_t>(n)); } int main() { char tpl[] = "./.qsave_verify_XXXXXX"; char *dir = ::mkdtemp(tpl); assert(dir != nullptr); const std::string cfg = std::string(dir) + "/calib.json"; const std::string v1 = R"({"schema_version":1,"zero":-15,"lim":420})"; { AtomicSaveTransaction tx(cfg); assert(tx.open_write()); assert(tx.write_all(v1)); assert(tx.commit()); } assert(read_file(cfg) == v1); { AtomicSaveTransaction aborted(cfg); assert(aborted.open_write()); assert(aborted.write_all(R"({"corrupt_half)")); // Leaves scope without commit() -> ~AtomicSaveTransaction() unlinks .tmp! } assert(::access((cfg + ".tmp").c_str(), F_OK) != 0); assert(read_file(cfg) == v1); ::unlink(cfg.c_str()); ::rmdir(dir); std::printf("savefile_audit: committed_bytes=%zu rollback_intact=1 tmp_cleaned=1\n", v1.size()); return 0; }- commit() flushes dirty pages via fsync(m_fd) BEFORE closing and executing atomic POSIX rename().
- Exiting scope without commit() triggers ~AtomicSaveTransaction() -> unlink(.tmp), keeping v1 intact.
Inspecting the Live Kernel strace Transcript of Commit and Rollback
Examine the strace capture below line by line! Transaction 1 executes openat(".../calib.json.tmp") -> write(...) -> fsync(...) -> rename(".../calib.json.tmp", ".../calib.json"), proving the live path was never truncated in place.
Immediately below it, Transaction 2 opens calib.json.tmp, writes "{\"corrupt_half", and calls unlink(".../calib.json.tmp") on scope exit—leaving calib.json untouched on disk.
learner@ksa:~/gl-q01/m06-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m06-l01./verifysavefile_audit: committed_bytes=41 rollback_intact=1 tmp_cleaned=1learner@ksa:~/gl-q01/m06-l01learner@ksa:~/gl-q01/m06-l01strace -e \trace=openat,write,fsync,rename,renameat,renameat2,unlink,exit_group ./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libstdc++.so.6", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libgcc_s.so.1", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libm.so.6", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json.tmp", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0600) = 3write(3, "{\"schema_version\":1,\"zero\":-15,\""..., 41) = 41fsync(3) = 0rename("./.qsave_verify_KmSvV3/calib.json.tmp", "./.qsave_verify_KmSvV3/calib.json") = 0openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json.tmp", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0600) = 3write(3, "{\"corrupt_half", 14) = 14unlink("./.qsave_verify_KmSvV3/calib.json.tmp") = 0openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json", O_RDONLY|O_CLOEXEC) = 3unlink("./.qsave_verify_KmSvV3/calib.json") = 0write(1, "savefile_audit: committed_bytes="..., 67) = 67exit_group(0) = ?+++ exited with 0 +++Filesystem Mount Boundaries, Missing QTextStream Flushes, and Flash Wear
QSaveFile turns fragile configuration writes into crash-atomic transactions with five lines of C++20. Next, Lesson 6.2 moves from flash persistence to 60 Hz visual rendering: custom QPainter gauges, premultiplied ARGB32 Porter-Duff math, and real-time QtCharts batching.
Note the target storage boundary: fsync() durability depends on the underlying eMMC controller honoring CACHE FLUSH (EXT_CSD cache control) on Linux kernel 6.12.
Staging Temporary Config Files in /tmp Before Calling rename() to /etc or /var:
- 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.
Calling QSaveFile::commit() at 50 Hz on Every Slider Drag Step:
- 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.
Guided Practice
Extend AtomicSaveTransaction::commit() in verify.cpp to also openat(AT_FDCWD, parent_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC) and fsync(dir_fd) right after rename(). Re-run under strace and observe the second fsync ensuring the directory entry itself is durable on freshly formatted ext4 partitions.
Independent Practice
Write a C++20 configuration loader with automatic .bak fallback that verifies a trailing CRC32 field inside the JSON object and rejects files whose schema version exceeds the running firmware's supported version.
Verification Checks
? check 1 · 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?
- [x]
~QSaveFile()automaticallyunlinks the temporary sibling file, leaving the previouscalib.jsoncompletely intact. - [ ]
~QSaveFile()flushes and renames the half-written temporary file overcalib.json. - [ ]
calib.jsonwas already truncated to0bytes whensf.open(QIODevice::WriteOnly)ran. - [ ] Both
calib.jsonand its parent directory are unlinked unlesssf.close()was called.
Answer: ~QSaveFile() automatically unlinks the temporary sibling file, leaving the previous calib.json completely intact.
Why: 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.
? check 2 · Why does QSaveFile create its temporary file in the same directory as the destination path instead of /tmp?
- [ ]
Linux kernel6.12 forbidsfsync()on file descriptors opened inside/tmp. - [ ]
QTextStreamcannot encodeQStringConverter::Utf8inside world-writable directories. - [ ]
/tmpstrips.jsonextensions from filenames longer than16bytes. - [x]
/tmpis commonly a separatetmpfsmount, and POSIXrename()fails withEXDEVacross filesystem mount boundaries.
Answer: /tmp is commonly a separate tmpfs mount, and POSIX rename() fails with EXDEV across filesystem mount boundaries.
Why: Atomic rename() only relinks directory entries within a single mounted filesystem.
Common misconception: Assuming rename("/tmp/cfg", "/var/lib/cfg") works atomically across mounts.
? check 3 · Why does calling sf.close() on a QSaveFile instance fail to compile in Qt 6?
- [ ]
close()requires passingQSignalBlockerby move reference in C++20. - [ ]
QSaveFilekeeps file descriptors open permanently untilQCoreApplication::exec()exits. - [x]
QSaveFiledeclaresclose()privateon purpose so callers must choosecommit()orcancelWriting()explicitly. - [ ]
QSaveFiledoes not inheritQIODeviceorQObjectin Qt 6.
Answer: QSaveFile declares close() private on purpose so callers must choose commit() or cancelWriting() explicitly.
Why: 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().
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.
Step sequence — frame strip: steps_m06_l01
Open QSaveFile at the target path so the temporary sibling resides on the same filesystem mount.
reveals: step1
highlights: step1
Serialize UTF-8 QJsonDocument or QTextStream content and abort via cancelWriting() on any short write.
reveals: step2
highlights: step2
Call QSaveFile::commit() (never close(), which is private) and check its boolean return status.
reveals: step3
highlights: step3
Parse with QFile(ReadOnly) + QJsonParseError and validate domain limits before applying settings.
reveals: step4
highlights: step4
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>).
Premultiplied Alpha Physics and the paintEvent Backing-Store Contract
In QtWidgets, every top-level window owns a software double-buffered backing store managed by QWidgetRepaintManager. You NEVER construct QPainter(this) inside a telemetry slot or call synchronous repaint() in a loop; instead, your setter updates m_kpa and calls update(), posting a coalesced UpdateRequest so paintEvent(QPaintEvent *ev) runs once per display frame with ev->region() bounding the exact dirty area.
When caching static bezel rings and tick marks into an off-screen QImage, always choose QImage::Format_ARGB32_Premultiplied over straight Format_ARGB32. Straight alpha blending must multiply source and destination channels by alpha AND divide by output alpha on every pixel! Premultiplied alpha stores (R*A/255, G*A/255, B*A/255) upfront, reducing Porter-Duff SourceOver to out = src + (dst * (255 - sa) + 127) / 255—pure integer multiplies and shifts with zero division!
Inside paintEvent, normalize DPI and resize math by translating (width()/2.0, height()/2.0) and scaling (side/200.0, side/200.0) so gauge geometry lives in a crisp [-100, +100] coordinate system—remembering that QPainter::drawArc integer angles are measured in 1/16th of a degree (360 * 16 = 5760)!
Figure 6.2a. Eliminating per-pixel division and per-sample chart re-layout on embedded Linux HMIs.
mental model: 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.
definition ( & QLineSeries::replace()): 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.
- Step 1. Guard setters for value changes and call asynchronous update() so Qt coalesces dirty regions.
- Step 2. Pre-render static bezel and tick geometry into QImage::Format_ARGB32_Premultiplied on resize.
- Step 3. Normalize coordinates via translate/scale and multiply integer drawArc angles by 16 (1/16th degree).
- Step 4. Update real-time QLineSeries traces once per frame via replace(QList<QPointF>) instead of per-point append().
Figure 6.2b. Paint in paintEvent via update(), cache ARGB32_Premultiplied, and batch series->replace().
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 QtCharts (QChart, QChartView, QLineSeries, and explicit QValueAxis bounds). The single most common QtCharts performance bug on embedded ARMv7-A Cortex-A7 boards is calling m_series->append(t, y) (and m_series->remove(0)) directly inside a 1 kHz sensor callback!
Every single append(x, y) emits pointAdded(int), marks the QGraphicsScene dirty, and triggers chart geometry bookkeeping—doing that 1,000 times per second starves the GUI event loop! Instead, ingest incoming samples into a plain C++ ring buffer, and on a 33 ms (30 Hz) UI frame timer build or rotate a QList<QPointF> buffer and call m_series->replace(m_framePoints).
Pair replace() with three QChart hardening settings: call chart->setAnimationOptions(QChart::NoAnimation) (animations interpolate every vertex on CPU!), attach fixed QValueAxis ranges (axisY->setRange(0, 500)) rather than auto-scaling every frame, and call chart->legend()->hide() on compact strip charts.
Figure 6.2b. Bit-level premultiplied ARGB32 layout and QtCharts real-time series architecture.
| Rendering Decision | High-Overhead Naive Choice | Production Qt 6 Choice | Measured Engineering Impact |
|---|---|---|---|
Off-screen QImage cache format | QImage::Format_ARGB32 (straight) | QImage::Format_ARGB32_Premultiplied | Eliminates format conversion & per-pixel alpha division |
| Scheduling widget redraws | Direct repaint() per packet | Value-guarded update() + ev->region() | Coalesces bursts into 1 VSync-paced paintEvent |
| Static gauge bezel & 60 ticks | Re-stroke sin/cos ticks every frame | Blit cached QImage rebuilt only in resizeEvent | Drops per-frame draw calls to dynamic arc + needle only |
QtCharts 1 kHz waveform | Per-sample series->append(x, y) | Ring buffer + 30 Hz series->replace(points) | 1 pointsReplaced() signal/frame instead of 1,000/s |
learner@ksa:~/gl-q01/m06-l02$ bat -H 58 -H 114 gauge_and_chart_panel.cpp File: gauge_and_chart_panel.cpp #include <QtCharts/QChart> #include <QtCharts/QChartView> #include <QtCharts/QLineSeries> #include <QtCharts/QValueAxis> #include <QHBoxLayout> #include <QImage> #include <QList> #include <QPaintEvent> #include <QPainter> #include <QPointF> #include <QWidget> #include <algorithm> class RadialPressureGauge final : public QWidget { Q_OBJECT public: explicit RadialPressureGauge(QWidget *parent = nullptr) : QWidget(parent) {} QSize minimumSizeHint() const override { return {120, 120}; } QSize sizeHint() const override { return {220, 220}; } void setPressureKpa(int kpa) { const int clamped = std::clamp(kpa, 0, 500); if (clamped == m_kpa) return; const bool wasHigh = (m_kpa >= m_alarmKpa); m_kpa = clamped; if ((m_kpa >= m_alarmKpa) && !wasHigh) emit alarmTriggered(m_kpa); update(); // Asynchronous coalesced repaint } signals: void alarmTriggered(int kpa); protected: void resizeEvent(QResizeEvent *ev) override { m_dialCache = QImage(); QWidget::resizeEvent(ev); } void paintEvent(QPaintEvent *ev) override { if (m_dialCache.isNull() || m_dialCache.size() != size()) rebuildCache(); QPainter p(this); p.setClipRegion(ev->region()); // Respect dirty-region clip! p.drawImage(0, 0, m_dialCache); p.setRenderHint(QPainter::Antialiasing, true); const double side = std::min(width(), height()); p.translate(width() / 2.0, height() / 2.0); p.scale(side / 200.0, side / 200.0); const QColor col = (m_kpa >= m_alarmKpa) ? QColor(0xDC, 0x26, 0x26) : QColor(0x0E, 0xA5, 0xE9); p.setPen(QPen(col, 10.0, Qt::SolidLine, Qt::FlatCap)); const int span16 = static_cast<int>((-240.0 * m_kpa / 500.0) * 16.0); p.drawArc(QRectF(-76.0, -76.0, 152.0, 152.0), 210 * 16, span16); } private: void rebuildCache() { m_dialCache = QImage(size(), QImage::Format_ARGB32_Premultiplied); m_dialCache.fill(Qt::transparent); QPainter cp(&m_dialCache); cp.setRenderHint(QPainter::Antialiasing, true); const double side = std::min(width(), height()); cp.translate(width() / 2.0, height() / 2.0); cp.scale(side / 200.0, side / 200.0); cp.setPen(QPen(QColor(0x33, 0x41, 0x55), 10.0)); cp.drawArc(QRectF(-76.0, -76.0, 152.0, 152.0), 210 * 16, -240 * 16); } int m_kpa = 0; int m_alarmKpa = 420; QImage m_dialCache; }; class BatchedWaveformStrip final : public QWidget { Q_OBJECT public: static constexpr int kWindow = 256; explicit BatchedWaveformStrip(QWidget *parent = nullptr) : QWidget(parent) { m_series = new QLineSeries(this); auto *chart = new QChart(); chart->setAnimationOptions(QChart::NoAnimation); chart->legend()->hide(); chart->addSeries(m_series); auto *axX = new QValueAxis(chart); axX->setRange(0.0, kWindow - 1); auto *axY = new QValueAxis(chart); axY->setRange(0.0, 500.0); chart->addAxis(axX, Qt::AlignBottom); chart->addAxis(axY, Qt::AlignLeft); m_series->attachAxis(axX); m_series->attachAxis(axY); m_points.resize(kWindow); for (int i = 0; i < kWindow; ++i) m_points[i] = QPointF(i, 0.0); auto *lay = new QHBoxLayout(this); lay->setContentsMargins(0, 0, 0, 0); lay->addWidget(new QChartView(chart, this)); } void pushSampleRing(double kpa) { m_ring[static_cast<std::size_t>(m_head)] = kpa; m_head = (m_head + 1) % kWindow; } void flushFrame30Hz() { for (int i = 0; i < kWindow; ++i) { const double y = m_ring[static_cast<std::size_t>((m_head + i) % kWindow)]; m_points[i].setY(y); } m_series->replace(m_points); // Single pointsReplaced() emission! } private: QLineSeries *m_series = nullptr; QList<QPointF> m_points; double m_ring[kWindow]{}; int m_head = 0; };- Static bezel ticks rasterize once into QImage::Format_ARGB32_Premultiplied on resize, avoiding per-frame trig.
- flushFrame30Hz() swaps all 256 ring samples via m_series->replace(m_points) in a single chart notification.
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 Lesson 6.2 QPainter-QtCharts(3qt) GL-Q01 quick reference · full manual page: man 3qt QPainter-QtCharts 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 SourceOver compositing inside a {20, 20, 60, 60} dirty clip rectangle, radial midpoint needle projection (250 kPa -> 90 deg -> (50, 15)), and a CLOCK_MONOTONIC comparison between 512 per-point append_single operations (recomputing bounds + notifying per point) versus one replace_batch pass!
Check both pixel invariants and notification counts: pixels outside the dirty clip remain 0xFF102030, blended channels satisfy c <= a, and replace_batch reduces layout notifications from 512 to 1.
learner@ksa:~/gl-q01/m06-l02$ bat -H 27 -H 71 verify.cpp File: verify.cpp #include <algorithm> #include <array> #include <cassert> #include <cmath> #include <cstdint> #include <cstdio> #include <ctime> #include <numbers> #include <vector> struct Rect { int x, y, w, h; constexpr bool contains(int px, int py) const noexcept { return px >= x && px < (x + w) && py >= y && py < (y + h); } }; static constexpr std::uint32_t pack_premul(std::uint8_t a, std::uint8_t r, std::uint8_t g, std::uint8_t b) noexcept { const std::uint32_t pr = (static_cast<std::uint32_t>(r) * a + 127U) / 255U; const std::uint32_t pg = (static_cast<std::uint32_t>(g) * a + 127U) / 255U; const std::uint32_t pb = (static_cast<std::uint32_t>(b) * a + 127U) / 255U; return (static_cast<std::uint32_t>(a) << 24U) | (pr << 16U) | (pg << 8U) | pb; } static constexpr std::uint32_t blend_over(std::uint32_t src, std::uint32_t dst) noexcept { const std::uint32_t sa = (src >> 24U) & 0xFFU; if (sa == 255U) return src; if (sa == 0U) return dst; const std::uint32_t inv = 255U - sa; auto ch = [inv](std::uint32_t s, std::uint32_t d, unsigned sh) { const std::uint32_t sc = (s >> sh) & 0xFFU; const std::uint32_t dc = (d >> sh) & 0xFFU; return std::min(255U, sc + (dc * inv + 127U) / 255U); }; return (ch(src, dst, 24U) << 24U) | (ch(src, dst, 16U) << 16U) | (ch(src, dst, 8U) << 8U) | ch(src, dst, 0U); } class PremulSurface { public: PremulSurface(int w, int h, std::uint32_t bg) : m_w(w), m_h(h), m_clip{0, 0, w, h}, m_px(static_cast<std::size_t>(w * h), bg) {} void set_clip(Rect c) noexcept { m_clip = c; } void blend_hline(int x0, int x1, int y, std::uint32_t premul) noexcept { for (int x = x0; x <= x1; ++x) { if (x >= 0 && x < m_w && y >= 0 && y < m_h && m_clip.contains(x, y)) { auto &d = m_px[static_cast<std::size_t>(y * m_w + x)]; d = blend_over(premul, d); } } } std::uint32_t pixel(int x, int y) const noexcept { return m_px[static_cast<std::size_t>(y * m_w + x)]; } private: int m_w, m_h; Rect m_clip; std::vector<std::uint32_t> m_px; }; class MockLineSeries { public: void append_single(double x, double y) { if (m_pts.size() == 512U) m_pts.erase(m_pts.begin()); m_pts.push_back({x, y}); recompute_scene_bounds(); // Per-point chart overhead! } void replace_batch(const std::vector<std::pair<double, double>> &batch) { m_pts = batch; recompute_scene_bounds(); // Single pass per frame! } int layout_passes = 0; double y_span = 0.0; private: void recompute_scene_bounds() noexcept { ++layout_passes; double lo = 1e9, hi = -1e9; for (const auto &p : m_pts) { lo = std::min(lo, p.second); hi = std::max(hi, p.second); } y_span = hi - lo; } std::vector<std::pair<double, double>> m_pts; }; static std::uint64_t mono_ns() noexcept { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } int main() { constexpr std::uint32_t bg = pack_premul(255, 16, 32, 48); PremulSurface surf(100, 100, bg); surf.set_clip({20, 20, 60, 60}); surf.blend_hline(50, 95, 50, pack_premul(128, 220, 38, 38)); const std::uint32_t inside = surf.pixel(60, 50); const std::uint32_t clipped = surf.pixel(85, 50); assert(clipped == bg && ((inside >> 24U) & 0xFFU) == 255U); const double rad = (210.0 - 240.0 * 250.0 / 500.0) * std::numbers::pi / 180.0; const int tip_x = 50 + static_cast<int>(std::lround(35.0 * std::cos(rad))); const int tip_y = 50 - static_cast<int>(std::lround(35.0 * std::sin(rad))); assert(tip_x == 50 && tip_y == 15); std::vector<std::pair<double, double>> frame(512); for (int i = 0; i < 512; ++i) frame[static_cast<std::size_t>(i)] = {double(i), double(i % 400)}; MockLineSeries s_append, s_replace; const std::uint64_t t0 = mono_ns(); for (const auto &pt : frame) s_append.append_single(pt.first, pt.second); const std::uint64_t append_ns = mono_ns() - t0; const std::uint64_t t1 = mono_ns(); s_replace.replace_batch(frame); const std::uint64_t replace_ns = mono_ns() - t1; assert(s_append.layout_passes == 512 && s_replace.layout_passes == 1); assert(s_append.y_span == s_replace.y_span); std::printf("render_audit: inside=0x%08X clipped=0x%08X tip=(%d,%d) append_ns=%llu replace_ns=%llu\n", inside, clipped, tip_x, tip_y, static_cast<unsigned long long>(append_ns), static_cast<unsigned long long>(replace_ns)); return 0; }- Porter-Duff SourceOver on premultiplied pixels blends in pure integer shift/multiply math without division.
- replace_batch swaps all 512 points and triggers 1 scene bounds pass instead of 512 per-point passes.
Verifying ARGB32 Blending, Clip Isolation, and QtCharts Batch Speedup
Confirm ./verify outputs inside=0xFF772326 clipped=0xFF102030 tip=(50,15) along with append_ns more than 100x slower than replace_ns! Pixels at (85, 50) stayed untouched outside {20, 20, 60, 60}, 250 kPa pointed straight to (50, 15), and batched replace cut layout passes from 512 to 1.
Next, Lesson 6.3 automates verification of custom gauges, signals, and interactive widgets inside headless Linux CI containers using QTest and QSignalSpy.
learner@ksa:~/gl-q01/m06-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m06-l02./verifyrender_audit: inside=0xFF76232B clipped=0xFF102030 tip=(50,15) append_ns=1122140 replace_ns=16678learner@ksa:~/gl-q01/m06-l02learner@ksa:~/gl-q01/m06-l02strace -e trace=write,exit_group ./verifywrite(1, "render_audit: inside=0xFF76232B "..., 98) = 98exit_group(0) = ?+++ exited with 0 +++Uninitialized QImage Garbage, 1/16th-Degree Arc Bugs, and Chart Animations
Premultiplied ARGB32 static layer caching and ring-buffered QLineSeries::replace() allow CPU-rendered QtWidgets dashboards to sustain crisp 60 Hz instrumentation without requiring a GPU shader pipeline.
Remember the hardware boundary: host benchmarks prove compositing and batching complexity, whereas display tearing and DRM/KMS page-flip latency must be verified on the target LCD controller.
Forgetting m_dialCache.fill(Qt::transparent) After Constructing QImage:
- 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).
Passing Whole Degrees Instead of 1/16th Degrees to QPainter::drawArc:
- 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).
Guided Practice
Add a channel-invariant verifier is_valid_premul(uint32_t px) to verify.cpp checking that pr <= a, pg <= a, and pb <= a for every pixel across surf after compositing three overlapping translucent strokes (alpha = 64, 128, 200), proving Porter-Duff SourceOver preserves premultiplied invariants.
Independent Practice
Write a fixed-capacity power-of-two WaveformRing<512> in C++20 supporting push_isr_sample(float) and copy_chronological(std::span<Point2D, 512>) with zero heap allocations on the 30 Hz render path.
Verification Checks
? check 1 · Why does Qt's raster paint engine strongly prefer QImage::Format_ARGB32_Premultiplied over straight QImage::Format_ARGB32 for off-screen QPainter caches?
- [ ] Straight
Format_ARGB32supports only 1-bit binary transparency (0or255). - [ ]
QPainter::Antialiasingis disabled by Qt wheneverFormat_ARGB32is selected. - [ ]
Format_ARGB32_Premultipliedcompresses pixels to16bits (RGB565) automatically. - [x] Premultiplied RGB channels already incorporate
alpha / 255, avoiding per-pixel alpha division and format conversions duringSourceOverblending.
Answer: Premultiplied RGB channels already incorporate alpha / 255, avoiding per-pixel alpha division and format conversions during SourceOver blending.
Why: 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.
? check 2 · What does painter.drawArc(rect, 90, 180) actually draw on screen?
- [ ] Nothing, because
drawArcrequires radians in[0, 2 * pi]. - [ ] A full
360-degree circle because90 + 180rounds up to5760. - [x] An
11.25-degree sliver starting at5.625degrees, because integerdrawArcangles are in1/16th-degree units (90 * 16and180 * 16are needed). - [ ] A
180-degree upper semicircle starting at12o'clock (90degrees).
Answer: An 11.25-degree sliver starting at 5.625 degrees, because integer drawArc angles are in 1/16th-degree units (90 * 16 and 180 * 16 are needed).
Why: 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().
? check 3 · 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?
- [ ] Wrap
series->append(x, y)insideQSaveFile::commit()so points stream through page cache. - [x] Buffer samples in a ring array, set
QChart::NoAnimation, and callseries->replace(pointsList)once on a30 Hzframe timer. - [ ] Call
chartView->repaint()immediately after everyseries->append(x, y)call. - [ ] Enable
QChart::AllAnimationssoQtChartsinterpolates intermediate points on a worker thread.
Answer: Buffer samples in a ring array, set QChart::NoAnimation, and call series->replace(pointsList) once on a 30 Hz frame timer.
Why: 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.
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.
Step sequence — frame strip: steps_m06_l02
Guard setters for value changes and call asynchronous update() so Qt coalesces dirty regions.
reveals: step1
highlights: step1
Pre-render static bezel and tick geometry into QImage::Format_ARGB32_Premultiplied on resize.
reveals: step2
highlights: step2
Normalize coordinates via translate/scale and multiply integer drawArc angles by 16 (1/16th degree).
reveals: step3
highlights: step3
Update real-time QLineSeries traces once per frame via replace(QList<QPointF>) instead of per-point append().
reveals: step4
highlights: step4
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.
Headless Offscreen QPA Execution and Why Thread Sleeps Starve QTimers
Many embedded teams skip automated GUI testing because they assume QtWidgets binaries require an X11 or Wayland display server and a physical monitor. Qt 6 solves this natively through its built-in offscreen Qt Platform Abstraction (QPA) plugin: running QT_QPA_PLATFORM=offscreen ./tst_panel -o -,tap inside a minimal Linux container executes real QLayout geometry, QValidator filters, QPainter off-screen grab() rendering, and QTimer dispatch with zero display daemons!
When testing asynchronous HMI behavior—such as a 20 ms debounce QTimer after an operator clicks Arm—engineers coming from multi-threaded C++ often write std::this_thread::sleep_for(50ms) before asserting spy.count() == 1. That test ALWAYS fails! Why? Because the test function runs on the main GUI thread: putting that thread to sleep freezes QEventLoop so the QTimer timeout event can never be dispatched!
QSignalSpy::wait(200) and QTRY_COMPARE(spy.count(), 1) spin a nested QEventLoop until the signal arrives (returning in 20 ms, not waiting the full 200 ms timeout!) or failing cleanly if timed out.
Figure 6.3a. End-to-end headless QtWidgets verification from synthetic input injection to TAP 13 CI gates.
mental model: 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.
definition ( & Offscreen QPA Plugin): 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).
- Step 1. Export QT_QPA_PLATFORM=offscreen and pass -o -,tap so headless CI runners parse TAP version 13 output.
- Step 2. Encode boundary vectors in companion _data() slots so every edge case reports an independent TAP line.
- Step 3. Simulate real operator clicks and typing via QTest::mouseClick and QTest::keyClicks rather than calling private slots.
- Step 4. Use QSignalSpy::wait() or QTRY_COMPARE so queued signals and QTimers dispatch on the test event loop.
Figure 6.3b. Run QT_QPA_PLATFORM=offscreen ./tst -o -,tap with _data(), mouseClick, and spy.wait().
Data-Driven _data Matrices, Synthetic Input Injection, and TAP 13 CI Gates
Qt6::Test pairs private test slots (void interlockMatrix()) with companion data-generator slots (void interlockMatrix_data()). Inside _data(), QTest::addColumn<T>(name) defines schema columns and QTest::newRow("case_name") << ... populates boundary vectors (below_limit, exact_limit, sustained_high_no_duplicate, estop_override), which QFETCH unpacks for each independent run.
Rather than calling internal helper methods directly, drive widgets through their public user surface with QTest::mouseClick(button, Qt::LeftButton) and QTest::keyClicks(lineEdit, "250"). That single habit tests isEnabled() gates, setAutoRepeat(false), QValidator states, and eventFilter hooks together—catching bugs where a slot works in isolation while its button was disabled or unparented!
Pass -o -,tap on the CI command line so QTest emits TAP version 13 (ok 1 - interlockMatrix(below_limit)), matching the exact TAP 13 harness contract used across every Kernel Systems Academy studio.
Figure 6.3b. Core Qt6::Test primitives for deterministic widget, signal, timer, and pixel regression suites.
| Verification Goal | Qt6::Test Primitive | Anti-Pattern to Ban | Why the Primitive Wins |
|---|---|---|---|
| Headless Docker/SSH execution | QT_QPA_PLATFORM=offscreen | Skipping GUI tests or spawning fragile Xvfb | Zero daemon dependencies; deterministic RAM surface |
| Simulate user button/key input | QTest::mouseClick / QTest::keyClicks | Calling private onArmClicked() slot directly | Verifies isEnabled(), QValidator, and eventFilter |
Await QTimer or queued signal | spy.wait(200) or QTRY_COMPARE | std::this_thread::sleep_for(200ms) | Pumps QEventLoop live; returns immediately on signal |
| Boundary & hysteresis coverage | slot_data() + QTest::newRow + QFETCH | Copy-pasting 6 nearly identical test methods | Reports exact failing row name in TAP version 13 |
learner@ksa:~/gl-q01/m06-l03$ bat -H 71 -H 85 tst_hmi_panel.cpp File: tst_hmi_panel.cpp #include <QLineEdit> #include <QPushButton> #include <QSignalSpy> #include <QTimer> #include <QtTest> class DebouncedSetpointBox final : public QWidget { Q_OBJECT public: explicit DebouncedSetpointBox(QWidget *parent = nullptr) : QWidget(parent) { m_edit = new QLineEdit(this); m_applyBtn = new QPushButton(tr("Apply"), this); m_applyBtn->setMinimumSize(44, 44); m_applyBtn->setAutoRepeat(false); connect(m_applyBtn, &QPushButton::clicked, this, [this] { bool ok = false; const int v = m_edit->text().toInt(&ok); if (!ok || v < 100 || v > 500) return; // Asynchronous 15 ms commit timer requiring an active QEventLoop! QTimer::singleShot(15, this, [this, v] { if (v >= 420 && !m_inAlarm) { m_inAlarm = true; emit alarmCrossed(v); } else if (v < 420) { m_inAlarm = false; } emit setpointApplied(v); }); }); } QLineEdit *editor() const noexcept { return m_edit; } QPushButton *applyButton() const noexcept { return m_applyBtn; } signals: void setpointApplied(int kpa); void alarmCrossed(int kpa); private: QLineEdit *m_edit = nullptr; QPushButton *m_applyBtn = nullptr; bool m_inAlarm = false; }; class TestHmiPanel final : public QObject { Q_OBJECT private slots: void alarmHysteresis_data() { QTest::addColumn<QString>("firstText"); QTest::addColumn<QString>("secondText"); QTest::addColumn<int>("expectedAlarms"); QTest::newRow("nominal_below_420") << QStringLiteral("250") << QStringLiteral("419") << 0; QTest::newRow("rising_edge_420") << QStringLiteral("419") << QStringLiteral("420") << 1; QTest::newRow("high_no_duplicate") << QStringLiteral("430") << QStringLiteral("460") << 1; } void alarmHysteresis() { QFETCH(QString, firstText); QFETCH(QString, secondText); QFETCH(int, expectedAlarms); DebouncedSetpointBox box; box.resize(240, 80); QSignalSpy appliedSpy(&box, &DebouncedSetpointBox::setpointApplied); QSignalSpy alarmSpy(&box, &DebouncedSetpointBox::alarmCrossed); QTest::keyClicks(box.editor(), firstText); QTest::mouseClick(box.applyButton(), Qt::LeftButton); QVERIFY(appliedSpy.wait(200)); // Pumps QEventLoop so 15 ms singleShot fires! box.editor()->clear(); QTest::keyClicks(box.editor(), secondText); QTest::mouseClick(box.applyButton(), Qt::LeftButton); QVERIFY(appliedSpy.wait(200)); QCOMPARE(appliedSpy.count(), 2); QCOMPARE(alarmSpy.count(), expectedAlarms); QCOMPARE(box.grab().toImage().size(), QSize(240, 80)); } }; // Run in CI: QT_QPA_PLATFORM=offscreen ./tst_hmi_panel -o -,tap QTEST_MAIN(TestHmiPanel) #include "tst_hmi_panel.moc"- appliedSpy.wait(200) pumps the thread event loop so QTimer::singleShot(15, ...) dispatches deterministically.
- Running with QT_QPA_PLATFORM=offscreen and -o -,tap executes headlessly and emits TAP version 13 lines.
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 Lesson 6.3 QTest-QSignalSpy(3qt) GL-Q01 quick reference · full manual page: man 3qt QTest-QSignalSpy Host C++20 Verifier for Event-Pumping SignalSpy::wait, Input Clicks, and Data Rows
In verify.cpp, we construct a C++20 MiniEventLoop, a DebouncedPanel scheduling asynchronous 15 ms commits, a variadic SignalSpy<int> implementing event-pumping wait(loop, timeout_ms), and a 4-row data-driven hysteresis runner.
Notice how verify.cpp also proves the thread-sleep anti-pattern directly: advancing wall wait WITHOUT pumping MiniEventLoop leaves applied_spy.count() == 0, whereas applied_spy.wait(loop, 200) pumps queued timers and wakes as soon as the 15 ms commit fires!
learner@ksa:~/gl-q01/m06-l03$ bat -H 42 -H 106 verify.cpp File: verify.cpp #include <algorithm> #include <cassert> #include <cstdio> #include <functional> #include <string> #include <tuple> #include <vector> class MiniEventLoop { public: void single_shot(int delay_ms, std::function<void()> cb) { m_timers.push_back({m_now_ms + delay_ms, std::move(cb)}); } void step_ms(int dt_ms) { m_now_ms += dt_ms; for (std::size_t i = 0; i < m_timers.size();) { if (m_timers[i].due_ms <= m_now_ms) { auto fn = std::move(m_timers[i].cb); m_timers.erase(m_timers.begin() + static_cast<std::ptrdiff_t>(i)); fn(); } else { ++i; } } } private: struct Timer { int due_ms; std::function<void()> cb; }; int m_now_ms = 0; std::vector<Timer> m_timers; }; template <typename... Args> class SignalSpy { public: void record(Args... a) { m_hits.emplace_back(a...); } std::size_t count() const noexcept { return m_hits.size(); } std::tuple<Args...> at(std::size_t i) const { return m_hits.at(i); } bool wait(MiniEventLoop &loop, int timeout_ms) { const std::size_t before = m_hits.size(); for (int elapsed = 0; elapsed < timeout_ms; elapsed += 5) { loop.step_ms(5); // Pumps event loop! if (m_hits.size() > before) return true; } return false; } private: std::vector<std::tuple<Args...>> m_hits; }; class DebouncedWidget { public: explicit DebouncedWidget(MiniEventLoop &loop, int alarm_kpa) : m_loop(loop), m_alarm(alarm_kpa) {} void key_clicks(std::string s) { m_text += s; } void clear_text() { m_text.clear(); } void mouse_click_apply() { if (!m_enabled) return; const int v = std::stoi(m_text); if (v < 100 || v > 500) return; m_loop.single_shot(15, [this, v] { if (v >= m_alarm && !m_in_alarm) { m_in_alarm = true; if (on_alarm) on_alarm(v); } else if (v < m_alarm) { m_in_alarm = false; } if (on_applied) on_applied(v); }); } std::function<void(int)> on_applied; std::function<void(int)> on_alarm; private: MiniEventLoop &m_loop; int m_alarm; bool m_enabled = true; bool m_in_alarm = false; std::string m_text; }; struct DataRow { const char *tag; std::vector<const char *> inputs; std::size_t exp_alarms; int first_alarm_val; }; int main() { const std::vector<DataRow> rows = { {"nominal_below", {"250", "419"}, 0U, 0}, {"exact_crossing", {"419", "420"}, 1U, 420}, {"sustained_high_no_dup", {"430", "460", "490"}, 1U, 430}, {"drop_and_recross", {"430", "380", "445"}, 2U, 430}, }; int ok_rows = 0; for (const auto &r : rows) { MiniEventLoop loop; DebouncedWidget w(loop, 420); SignalSpy<int> applied_spy, alarm_spy; w.on_applied = [&](int v) { applied_spy.record(v); }; w.on_alarm = [&](int v) { alarm_spy.record(v); }; for (const char *txt : r.inputs) { w.clear_text(); w.key_clicks(txt); w.mouse_click_apply(); // Without pumping loop, queued 15ms timer has NOT fired yet: assert(applied_spy.wait(loop, 200)); } assert(alarm_spy.count() == r.exp_alarms); if (r.exp_alarms > 0U) assert(std::get<0>(alarm_spy.at(0)) == r.first_alarm_val); ++ok_rows; } assert(ok_rows == 4); std::printf("qtest_audit: tap_rows=%d/4 spy_wait_pumped=1 platform=offscreen\n", ok_rows); return 0; }- SignalSpy::wait() steps the event loop incrementally and returns immediately as soon as a new emission arrives.
- Each _data() row runs in an isolated widget/loop instance, proving rising-edge hysteresis and re-crossing.
Verifying Data-Driven Hysteresis Rows and Event-Pumping SignalSpy Output
Confirm ./verify prints qtest_audit: tap_rows=4/4 spy_wait_pumped=1 platform=offscreen. Every single boundary vector—nominal below-alarm, exact 420 crossing, sustained high without duplicate spam, and drop-below-then-recross—matched its exact SignalSpy count and argument payload.
You are ready for the Module 6 Capstone Studio lab_m06_qpainter_gauge_qtest, uniting crash-atomic calibration persistence, premultiplied ARGB32 gauge rasterization + batched waveform replacement, and rising-edge SignalSpy verification into one end-to-end subsystem.
learner@ksa:~/gl-q01/m06-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m06-l03./verifyqtest_audit: tap_rows=4/4 spy_wait_pumped=1 platform=offscreenlearner@ksa:~/gl-q01/m06-l03learner@ksa:~/gl-q01/m06-l03strace -e trace=write,exit_group ./verifywrite(1, "qtest_audit: tap_rows=4/4 spy_wa"..., 63) = 63exit_group(0) = ?+++ exited with 0 +++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.8 QtWidgets: and QObject trees, CMake AUTOMOC and moc void ** metacalls, PMF signal lifetimes and eventFilter chains, two-step button interlocks and integer layout solvers, 50,000-row QAbstractTableModel + proxy views, QSaveFile atomicity, premultiplied ARGB32 gauges + batched QtCharts, and headless QTest TAP 13 automation.
Next in the series, GL-Q02 (linux-qt-io-concurrency) scales your HMIs across QThread worker pipelines, lock-free SPSC rings, QTcpSocket/QSerialPort/SocketCAN buses, SQLite WAL storage, and cross-compiled ARMv7-A CMake sysroots.
Calling std::this_thread::sleep_for or QThread::msleep Inside a QTest Slot:
- 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().
Defining a Q_OBJECT Test Class Inside tst_panel.cpp Without #include 'tst_panel.':
- Symptom: Linker fails with 'undefined reference to for TestHmiPanel' or QTest executes 0 private test slots.
- Root Cause: 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).
Guided Practice
Add a fifth row "invalid_out_of_range" (inputs = {"999", "50"}) to rows in verify.cpp where mouse_click_apply() rejects out-of-range strings without scheduling the 15 ms timer, and assert that !applied_spy.wait(loop, 50) times out cleanly with applied_spy.count() == 0.
Independent Practice
Complete the GL-Q01 Capstone Project (lab_m06_qpainter_gauge_qtest) by repairing the three starter defects across atomic calibration fsync + rename rollback, premultiplied ARGB32 SourceOver blending, and rising-edge GaugeController alarm hysteresis.
Verification Checks
? check 1 · 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?
- [ ]
QT_Quick_BACKEND=software ./tst_hmi_panel -platform linuxfb - [ ]
DISPLAY=:0 ./tst_hmi_panel -o tap13.xml - [x]
QT_QPA_PLATFORM=offscreen ./tst_hmi_panel -o -,tap - [ ]
CMAKE_AUTOMOC=1 ./tst_hmi_panel --tap13 --no-x11
Answer: QT_QPA_PLATFORM=offscreen ./tst_hmi_panel -o -,tap
Why: 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.
? check 2 · 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?
- [ ]
QT_QPA_PLATFORM=offscreendisablesCLOCK_MONOTONICtimer file descriptors. - [x]
sleep_forblocks the calling GUI thread soQEventLoopcannot process timer expirations during the sleep. - [ ]
std::this_thread::sleep_forresetsQTimerintervals to zero under-std=c++20. - [ ]
QSignalSpydisconnects automatically whenever<thread>functions execute.
Answer: sleep_for blocks the calling GUI thread so QEventLoop cannot process timer expirations during the sleep.
Why: 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.
? check 3 · Why is driving a test via QTest::mouseClick(applyBtn, Qt::LeftButton) stronger than calling panel.applySetpoint(420) directly?
- [x]
mouseClickexercisesisEnabled()interlocks, hit-box geometry,autoRepeatsettings, and installedeventFilterhooks along the real delivery path. - [ ]
QSignalSpyonly records signals emitted duringQTest::mouseClickand ignores direct C++ calls. - [ ]
mouseClickautomatically runsfsync()onQSaveFileinstances attached to the widget. - [ ] Direct method calls fail to compile inside
private slots:of aQTestclass.
Answer: mouseClick exercises isEnabled() interlocks, hit-box geometry, autoRepeat settings, and installed eventFilter hooks along the real delivery path.
Why: 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.
1. Motivation
Integrate and verify an end-to-end C++20 HMI Gauge Capstone uniting QSaveFile-style fsync + rename calibration persistence, clipped premultiplied ARGB32 SourceOver rasterization, ring-buffered waveform snapshots, and QSignalSpy-style rising-edge hysteresis tests.
2. Learning objectives
- Guarantee crash-atomic configuration saves via
openat(.tmp) -> write -> fsync -> renameand clean.tmpunlinking on abort. - Enforce dirty-region
ClipRectboundaries and premultiplied ARGB32 Porter-DuffSourceOvercompositing on custom gauge needles. - Verify tare-compensated rising-edge alarm hysteresis and chronological ring-buffer waveform batches for
QLineSeries::replace().
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7industrial HMI panel (800x480RGB LCD,8 GBeMMC) runningLinux kernel6.12 LTS, Qt 6.8QtWidgets+QtCharts, and headless CI gates underQT_QPA_PLATFORM=offscreen -o -,tap.
5. Complete executable commands
learner@ksa:~/gl-q01/m06-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/m06-l03$ bat example.cpp File: example.cpp void GaugeController::set_raw_kpa(int raw_sensor_kpa) { const int comp = std::clamp(raw_sensor_kpa + m_cal.zero_offset_kpa, 0, 500); m_ring[m_head] = comp; m_head = (m_head + 1U) % m_ring.size(); if (m_count < m_ring.size()) ++m_count; if (comp == m_compensated_kpa) return; const bool was_alarm = (m_compensated_kpa >= m_cal.alarm_kpa); m_compensated_kpa = comp; const bool now_alarm = (m_compensated_kpa >= m_cal.alarm_kpa); if (now_alarm && !was_alarm && on_alarm) { on_alarm(m_compensated_kpa); // Rising-edge hysteresis only! } }starter/core.cpp contains three realistic capstone bugs: save_calibration_atomic leaks .tmp on abort, ArgbCanvas::put_pixel ignores m_clip.contains(x, y), and GaugeController::set_raw_kpa fires on_alarm on every sample while high instead of only on rising-edge crossings.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/m06-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - commits calibration atomically via fsync+rename and unlinks .tmp cleanly on abort ok 4 - composites premultiplied ARGB32 SourceOver strokes strictly inside dirty ClipRect bounds ok 5 - applies zero-offset tare, latches rising-edge alarm spy counts, and batches ring waveforms # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-q01/m06-l03$ bat listing.txt File: listing.txt capstone_gauge: comp_kpa=430 alarms=1 center_argb=0xFFDC2626 wave_pts=3Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
Check 3 commits {-15, 380} via fsync + rename, triggers a simulated abort on {+99, 450}, confirms .tmp was unlinked, and reloads intact {-15, 380}. Check 4 draws a 50% translucent stroke across {10, 10, 40, 40}, proving premultiplied blending inside the clip and untouched background at (60, 20). Check 5 drives GaugeController across five tare-compensated readings, asserting rising-edge spy hits {405, 410}, 4-point chronological ring ordering, and alarm-crimson (220) needle rendering.
9. Experiment variations
- Near transfer: Add a falling-edge hysteresis deadband (
clear_alarm_kpa = alarm_kpa - 15) som_in_alarmstays latched until pressure drops at least15 kPabelowalarm_kpa, preventing alarm chatter at399 <-> 400 kPa. - Far transfer: Port
GaugeControllerandTestHmiPanelinto a CMakeQt6::Widgets+Qt6::Charts+Qt6::Testtarget and executeQT_QPA_PLATFORM=offscreen ctest --output-on-failurein your CI container.
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/m06-l03$ bat listing.txt File: listing.txt bench_gauge_render_ns: p50=1123 p95=1464 p99=1964 (sink=0)The CLOCK_MONOTONIC benchmark measures combined host C++20 set_raw_kpa + 160x160 software Bresenham needle rasterization + 256-sample waveform batch snapshot latency in DRAM. Target 60 Hz frame budgets (16.67 ms) on Cortex-A7 hardware must also include QChart polyline rasterization and DRM scanout.
11. Troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
| Check 3 fails with aborted save leaked .tmp file | simulate_abort closed fd without calling ::unlink(tmp.c_str()) | Call ::unlink(tmp.c_str()) on every error and abort path before returning false |
| Check 4 fails with dirty clip violated at (60,20) | ArgbCanvas::put_pixel bypassed !m_clip.contains(x, y) | Restore !m_clip.contains(x, y) in the early-return guard of put_pixel() |
| Check 5 fails with rising-edge alarm spy count=3 (expected 2) | on_alarm emitted whenever now_alarm was true without checking !was_alarm | Emit on_alarm only when (now_alarm && !was_alarm) |
12. Guided questions
- Why does snapshot_waveform_batch() copy ring elements starting at m_head once m_count == m_ring.size()?
- *Hint 1:* Trace where the oldest sample sits in a circular buffer after wrap-around.
- *Hint 2:* Once full, m_head points to the next slot to be overwritten—which is the oldest surviving sample—so reading (m_head + i) % N yields chronological left-to-right chart order.
- Why is rising-edge + deadband hysteresis essential when wiring a gauge threshold signal to a FaultLogModel?
- *Hint 1:* Imagine ADC thermal noise oscillating 399 -> 400 -> 399 -> 400 kPa at 500 Hz.
- *Hint 2:* Without rising-edge gating and hysteresis, 1-LSB ADC noise floods the fault log and operator buzzer with 250 duplicate alarms per second.
13. Independent challenges
Extend ArgbCanvas with Wu anti-aliased line rasterization (pack_premul_argb32 fractional coverage alphas) and verify every blended pixel across a 360-degree sweep maintains the premultiplied invariant R', G', B' <= A.
14. Solutions and explanations
Transactional fsync + rename + unlink persistence, dirty-clipped premultiplied ARGB32 compositing, batched ring-buffer waveform snapshots, and rising-edge SignalSpy tests complete a production-grade Qt 6 HMI.
Run locally in your terminal and check off each verification milestone.
Not started
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.
Step sequence — frame strip: steps_m06_l03
Export QT_QPA_PLATFORM=offscreen and pass -o -,tap so headless CI runners parse TAP version 13 output.
reveals: step1
highlights: step1
Encode boundary vectors in companion _data() slots so every edge case reports an independent TAP line.
reveals: step2
highlights: step2
Simulate real operator clicks and typing via QTest::mouseClick and QTest::keyClicks rather than calling private slots.
reveals: step3
highlights: step3
Use QSignalSpy::wait() or QTRY_COMPARE so queued signals and QTimers dispatch on the test event loop.
reveals: step4
highlights: step4