QBoxLayout, QGridLayout, QFormLayout, QSpacerItem & Stretch Solvers

Compute pixel-exact widget coordinates across 800x480 to 1920x1080 displays using QBoxLayout, QGridLayout, QFormLayout, QSpacerItem, QSizePolicy flags, and drift-free integer stretch division.

30 minfree previewLinux 6.12→ module 4 lab
What you'll learn
  • Derive exact 1D/2D widget positions and sizes from margins, visible-only spacing gaps, sizeHint(), minimumSizeHint(), and QSizePolicy.
  • Distribute surplus pixels across integer stretch weights with maxSize cap redistribution and remainder rounding so zero cumulative drift occurs.
  • Structure aligned multi-channel readouts and calibration dialogs using QGridLayout, QFormLayout, and QSpacerItem without nested parent collisions.

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!

fig_m04_l03_a.svg — Constraint-based geometry calculation across visible…

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.

ast_m04_l03.svg — Ban magic setGeometry(); use QGridLayout/QFormLayout,…step 1/4
  1. Step 1. Compute usable span U from visible items only: hidden widgets contribute 0 px size and 0 spacing gaps.
  2. Step 2. Iteratively clamp items that hit maximumSize() so uncapped stretchable siblings absorb the leftover pixels.
  3. Step 3. Distribute integer division remainders deterministically so right/bottom edges align to the exact pixel.
  4. 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).

fig_m04_l03_b.svg — Choosing between QBoxLayout, QGridLayout, QFormLayout,…

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

Layout / Item TypeDimensionalitySurplus Space RuleTypical Engineering Pattern
QHBoxLayout / QVBoxLayout1D horizontal or verticalstretch > 0 first, then Expanding, then PreferredToolbars, action footers, vertical panel stacks
QGridLayout2D (row, col, rowSpan, colSpan)setColumnStretch(c, w) & setRowStretch(r, w)Multi-channel (Name, Value, Unit) sensor matrices
QFormLayout2-column (label, field) pairsFieldGrowthPolicy (ExpandingFieldsGrow / AllNonFixedFieldsGrow)Calibration offset, network, and serial-port forms
QSpacerItem (addStretch)Lightweight QLayoutItemQSizePolicy::Expanding spring (0 QWidget overhead)Right-aligning status badges or bottom-pinning footers
learner@ksa: ~/gl-q01/m04-l03
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);        }    };
  1. Child sub-layouts (grid, form, footer) construct with no parent QWidget* and attach cleanly via root->addLayout().
  2. setColumnStretch(1, 1) routes all surplus width into the numeric value column while keeping labels and units compact.
QLayout-QSizePolicy(3qt) at a glance — GL-Q01
QLayout-QSizePolicy(3qt)    GL-Q01 Quick Reference    QLayout-QSizePolicy(3qt) NAME       QBoxLayout, QGridLayout, QFormLayout, QSpacerItem, QSizePolicy - Qt 6       geometry solvers SYNOPSIS       auto *root = new QVBoxLayout(this); // ONLY the top-level layout takes       'this' auto *grid = new QGridLayout(); // sub-layouts take no parent;       call root->addLayout(grid) grid->setColumnStretch(1, 1); //       proportional track weight box->addStretch(1); // inserts Expanding       QSpacerItem (zero QWidget overhead)        SOLVER EQUATION (1D AXIS) usable = max(0, total - marginStart -       marginEnd - (N_visible - 1) * spacing) Priority: (1) stretch > 0, (2)       QSizePolicy::Expanding, (3) QSizePolicy::Preferred Kernel Systems Academy           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
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;    }
  1. Gap count uses (vis.size() - 1) * spacing so hidden items leave zero orphan gaps between visible neighbors.
  2. 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-l03
learner@ksa:~/gl-q01/m04-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m04-l03./verifylayout_audit: rem=[101,101,100] end=312 hidden_pos2=118 capped=[130,270]learner@ksa:~/gl-q01/m04-l03
strace — learner@ksa: ~/gl-q01/m04-l03
learner@ksa:~/gl-q01/m04-l03strace -e trace=write,exit_group ./verifywrite(1, "layout_audit: rem=[101,101,100] "..., 73) = 73exit_group(0)                           = ?+++ exited with 0 +++

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

quiz · 1 of 3

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

quiz · 2 of 3

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?

quiz · 3 of 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?

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

env: host

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) * spacing gap deductions.
  • Redistribute surplus pixels iteratively when a stretchable item saturates max_px, and align multi-row 2D solve_grid tracks.

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), GNU make, ar (binutils), and POSIX /bin/sh.
  • Target environment (optional hardware step, Section 13): ARMv7-A Cortex-A7 HMI panel (800x480 RGB LCD or 1024x600 LVDS) running Linux kernel 6.12 LTS and Qt 6.8 QtWidgets, verified across 96 DPI and 144 DPI font-scaling profiles.

5. Complete executable commands

learner@ksa: ~/gl-q01/m04-l03
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.sh

6. Annotated source code

files/core.cpp enforces the production invariants that starter/core.cpp breaks:

learner@ksa: ~/gl-q01/m04-l03
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
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/5

CLI verification output (./files/lab_cli):

learner@ksa: ~/gl-q01/m04-l03
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=290

Defective 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_span support (col_span == 2) to GridCell so a section header banner spans columns 0..1 with width x_tracks[0].size + h_spacing + x_tracks[1].size.
  • Far transfer: Implement QFormLayout-style two-column row solving where right-aligned column-0 labels lock to the widest label's hint_px while column-1 editors expand up to max_px.

10. Performance measurements

Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):

learner@ksa: ~/gl-q01/m04-l03
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

SymptomRoot causeFix
Check 3 fails with right_edge=310 instead of 312Starter code zeroes surplus instead of distributing 1px remaindersIncrement 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 20pxKeep if (capped_any && gained > 0) continue; active before remainder loop

12. Guided questions

  1. 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.
  1. 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

Key takeaways

  • QLayoutEngine subtracts margins and (N_visible - 1) * spacing first, locks QSizePolicy::Fixed items to sizeHint(), clamps [minimumSize, maximumSize], and divides surplus across stretch factors without cumulative rounding drift.
  • Hidden widgets (!isVisible()) consume zero pixels and zero inter-item spacing gaps, while QSpacerItem (addStretch) absorbs slack space without allocating a QWidget window backing surface.
  • QGridLayout solves shared column and row tracks (setColumnStretch, setRowStretch) across multi-row telemetry cells, whereas QFormLayout pairs two-column label-and-field calibration rows cleanly.
  • Passing a QWidget * constructor argument to a nested sub-layout (new QHBoxLayout(this)) fails because a QWidget owns only one root layout; nested layouts construct parentless and attach via addLayout().
Progress is saved on this device.
up next · module 4 labLab: 1D/2D Box & Grid Layout Geometry Solver with Max-Cap Redistribution (70 min)
→ module 4 lab

search — fzf

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

keyboard shortcuts — less

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

figure