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.
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 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
→ open standalone lab workbench
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
Key takeaways
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().