Buttons, Checkable Groups & Safety Interlocks
Unify multi-surface commands behind QAction, enforce mutual exclusion and tristate rollups via QButtonGroup and QCheckBox, and harden 44x44 px QPushButton actuators against auto-repeat bounce.
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
Key takeaways
- 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.