Qt Designer .ui XML, uic setupUi() Generation & Code-First HMIs

Trace how uic compiles Designer .ui XML files into plain C++ Ui::Panel::setupUi() headers at build time, and replace brittle connectSlotsByName naming magic with explicit PMF connect.

25 minfree previewLinux 6.12→ module 2 lab
What you'll learn
  • Dissect every statement emitted by uic inside Ui_Panel::setupUi(QWidget *) and retranslateUi(QWidget *).
  • Eliminate silent field regressions from on_<objectName>_<signal> slots by enforcing explicit pointer-to-member QObject::connect wiring.
  • Architect clean private Ui::Panel wrappers and parameterized code-first channel strips with stable objectName test 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!

fig_m02_l02_a.svg — uic emits ordinary C++ widget allocations in ui_*.h,…

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; }!

ast_m02_l02.svg — Hold Ui::Form privately via unique_ptr, ban…step 1/4
  1. Step 1. Forward-declare Ui::PumpPanel in pump_panel.hpp and hold std::unique_ptr<Ui::PumpPanel> m_ui privately.
  2. Step 2. Call m_ui->setupUi(this) inside the constructor body and define ~PumpPanel() = default in .cpp.
  3. Step 3. Connect every m_ui control with compile-time pointer-to-member QObject::connect calls.
  4. 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!

fig_m02_l02_b.svg — Ui_PumpPanel is a non-QObject struct of observer…

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 ApproachGit Diff & Review ClarityRefactor / Rename SafetyIdeal Industrial Use Case
Designer .ui + connectSlotsByNameVerbose XML diffs on minor coordinate nudgesUnsafe: renaming widget breaks on_name_sig at runtimeAvoid in production safety or mission-critical HMIs
Designer .ui + Private m_ui + PMF connectXML layout separated from .cpp controller logicHigh: renaming widget breaks m_ui->widget at compile timeFixed settings dialogs and static calibration forms
Code-First C++ Loops (QHBoxLayout / QGridLayout)Compact 5-20 line C++ diffs; trivial branch mergesHighest: 100% typed C++ identifiers and constexpr countsMulti-channel telemetry strips, dynamic status matrices
Runtime QUiLoader (.ui parsed on target)Requires shipping XML + QtUiTools libraryLowest: all widget lookups via findChild stringsRare user-customizable plugin forms only
learner@ksa: ~/gl-q01/m02-l02
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{};    };
  1. uic emits plain C++ heap allocations parented to PumpPanel and delegates text assignment to retranslateUi().
  2. Explicit PMF connect binds m_ui->haltDriveBtn to a signal-to-signal forwarder checked at compile time.
uic(1) at a glance — GL-Q01
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
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;    }
  1. setup_ui() builds 4 parameterized channel QLabel nodes plus the action button under host.children.
  2. 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-l02
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-l02
strace — learner@ksa: ~/gl-q01/m02-l02
learner@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 .cpp files.
  • Root Cause: Inheriting public Ui::Panel exposes every generated raw child pointer in Ui_Panel as part of Panel's public C++ API, destroying encapsulation.
  • Fix: Store std::unique_ptr<Ui::Panel> m_ui; (or Ui::Panel m_ui; inside .cpp-only classes) under private: and expose semantic controller methods (setDriveArmed(bool)) and signals (emergencyHaltRequested()).

Placing Fixed Pixel setGeometry() Widgets Without a Root QLayout in Designer:

  • Symptom: A .ui panel looks aligned at 800x480 in Designer, then clips half its buttons at 1024x600 or 1280x800 DPI scaling on target hardware.
  • Root Cause: Dropping widgets onto a Designer canvas without applying a top-level QVBoxLayout/QGridLayout makes uic emit hardcoded setGeometry(QRect(x, y, w, h)) pixel coordinates!
  • Fix: Always assign a top-level layout on the form root in Designer (verify no red 'broken layout' icon appears in the Object Inspector) so uic emits QLayout::addWidget rules.

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

quiz · 1 of 3

Which runtime file from status_panel.ui must be installed onto the embedded ARMv7-A root filesystem when built via CMAKE_AUTOUIC?

quiz · 2 of 3

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)?

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

Key takeaways

  • During a CMAKE_AUTOUIC build, uic compiles panel.ui XML ahead-of-time into ui_panel.h containing Ui_Panel::setupUi() and retranslateUi(), shipping zero XML files or XML parsers to the target.
  • Composing std::unique_ptr<Ui::Panel> m_ui as a private member encapsulates generated child widget pointers, whereas public Ui::Panel inheritance leaks internal controls to external callers.
  • QMetaObject::connectSlotsByName matches on_<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::connect calls.
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure