Containers, Display Widgets & Lazy Page Budgets
Compose multi-page operator workbenches from QStackedWidget, QTabWidget, QScrollArea, QToolBox, QDockWidget, QMdiArea, and passive readouts while deferring off-screen page allocations.
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
Key takeaways
- 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.