Numeric/Text Editors, QValidator States & QSignalBlocker Anti-Echo

Gate operator text entry with three-state QValidator automata, choose bounded QPlainTextEdit log buffers over rich-text DOM trees, and synchronize coupled setpoint controls cleanly with QSignalBlocker.

35 minfree previewLinux 6.12→ module 4 lab
What you'll learn
  • Classify live keystrokes into QValidator::Invalid, Intermediate, and Acceptable states so multi-digit numeric edits progress without premature commits.
  • Eliminate recursive valueChanged ping-pong across coupled QSpinBox, QDoubleSpinBox, QSlider, QDial, QComboBox, and QLineEdit controls using RAII QSignalBlocker.
  • Select QPlainTextEdit (maximumBlockCount) versus QTextEdit/QTextBrowser and fixed-point integer backing to bound RAM and avoid IEEE-754 drift.

Prefix Validation Automata and Coupled-Control Signal Ping-Pong

Consider a manifold pressure QLineEdit constrained to [100, 500] kPa. A naive keystroke filter that rejects every integer below 100 makes typing '250' impossible because the very first keystroke '2' is less than 100! Qt's QValidator resolves this cleanly with three states: '25x' or '999' returns Invalid (discarded immediately), "" or '2' or '25' returns Intermediate (accepted into the buffer while suppressing editingFinished()), and '250' returns Acceptable.

A companion hazard lurks inside QSpinBox and QDoubleSpinBox: by default, keyboardTracking() is true, so typing '2', '5', '0' emits valueChanged on every valid intermediate keystroke! Calling setKeyboardTracking(false) withholds valueChanged until the operator presses Enter, leaves focus, or clicks an arrow step.

Once committed, dashboards often mirror one setpoint across a QSpinBox, a coarse QSlider or QDial, and a QLineEdit. Without QSignalBlocker, spin->setValue(243) updates slider to 240 (5-unit tick), which fires slider->valueChanged(240) right back to overwrite spin with 240!

fig_m04_l02_a.svg — Keystroke validation and multi-widget setpoint…

Figure 4.2a. Keystroke validation and multi-widget setpoint synchronization without recursive signal echo.

mental model: QValidator::Intermediate works like an airlock keypad expecting a three-digit pressure code between 100 and 500: pressing '2' neither buzzes an error nor opens the inner hatch—it holds the latch in an in-progress state until '5' and '0' complete '250' (Acceptable), while rejecting 'x' (Invalid) on sight.

Where it stops working: An airlock keypad is a single input terminal, whereas coupling a QLineEdit, QSpinBox, and quantized QSlider on one screen creates an active feedback loop where one programmatic setValue() echoes back into its sender unless silenced by QSignalBlocker.

definition ( & QValidator::State): QValidator::State (Invalid = 0, Intermediate = 1, Acceptable = 2) models formal prefix-language acceptance so QLineEdit permits valid prefixes ("", "-", "25" on [100, 500]) while gating editingFinished() on Acceptable. QSignalBlocker is a non-copyable C++ guard calling m_wasBlocked = obj->blockSignals(true) in its constructor and obj->blockSignals(m_wasBlocked) in its destructor.

ast_m04_l02.svg — Gate commits on QValidator::Acceptable, sync peers with…step 1/4
  1. Step 1. Let QValidator::Intermediate pass valid numeric prefixes without firing editingFinished prematurely.
  2. Step 2. Disable keyboardTracking on setpoint spinboxes so hardware sees only committed Enter, focus-out, or step clicks.
  3. Step 3. Wrap programmatic setValue/setText calls in stack-scoped QSignalBlocker guards to preserve outer block states.
  4. Step 4. Cap console RAM with QPlainTextEdit::setMaximumBlockCount and store QComboBox enum payloads via currentData().

Figure 4.2b. Gate commits on QValidator::Acceptable, sync peers with QSignalBlocker, and cap logs.

QSignalBlocker RAII, QPlainTextEdit vs QTextBrowser, and Typed Selectors

Legacy code often wraps programmatic updates in slider->blockSignals(true); slider->setValue(v); slider->blockSignals(false);. That pattern has two defects: an early return leaves the widget permanently mute, and blockSignals(false) unconditionally unblocks a widget that an outer diagnostic caller had intentionally silenced! const QSignalBlocker b(slider); captures the return value of blockSignals(true) and restores that exact prior boolean in ~QSignalBlocker().

For multi-line text, pick the engine that matches the workload. QTextEdit and read-only QTextBrowser construct a rich-text QTextDocument DOM supporting HTML tables, CSS, and hyperlinks—ideal for static help manuals, fatal for a 115200-baud serial trace! QPlainTextEdit uses a lightweight plain-text layout and setMaximumBlockCount(500), automatically evicting the oldest line block in O(1) when line 501 arrives.

Round out forms with typed selectors: pass QVariant integer IDs to QComboBox::addItem(tr("psi"), UnitPsi) and read combo->currentData().toInt() so switching UI languages never breaks unit math, and call QDateTimeEdit::setTimeZone(QTimeZone::UTC) so daylight-saving transitions never fold log query windows.

fig_m04_l02_b.svg — Memory and precision contracts across Qt 6 text,…

Figure 4.2b. Memory and precision contracts across Qt 6 text, numeric, selector, and log widgets.

Editor / Display ClassInternal Backing ModelCritical Configuration CallPrimary HMI Use Case
QLineEdit + QValidatorSingle-line UTF-16 buffersetValidator(new QIntValidator(lo, hi, this))Constrained codes, IP/hex tokens, validated numeric text
QSpinBox / QDoubleSpinBoxDiscrete int / doublesetKeyboardTracking(false)Precision stepped setpoints without mid-typing glitches
QSlider / QDialBounded QAbstractSliderWrap programmatic setValue in QSignalBlockerCoarse analog-style jog/trim mirrors coupled to spinboxes
QComboBox + QDateTimeEditQStandardItemModel / QDateTimeaddItem(text, enumVal) & setTimeZone(QTimeZone::UTC)Translation-safe enum pickers and unambiguous UTC log filters
QPlainTextEdit vs QTextBrowserPlain blocks vs HTML QTextDocumentplain->setMaximumBlockCount(500)Live streaming bus logs (Plain) vs hyperlinked help (Browser)
learner@ksa: ~/gl-q01/m04-l02
learner@ksa:~/gl-q01/m04-l02$ bat -H 31 -H 83 coupled_setpoint_console.cpp File: coupled_setpoint_console.cpp    #include <QComboBox>    #include <QDateTime>    #include <QDateTimeEdit>    #include <QDial>    #include <QHBoxLayout>    #include <QIntValidator>    #include <QLineEdit>    #include <QPlainTextEdit>    #include <QSignalBlocker>    #include <QSlider>    #include <QSpinBox>    #include <QTimeZone>    #include <QVBoxLayout>    #include <QWidget>    #include <algorithm>        class CoupledSetpointConsole final : public QWidget {        Q_OBJECT    public:        enum PressureUnit : int { UnitKpa = 1, UnitBarX100 = 2 };        static constexpr int kMinKpa = 100;        static constexpr int kMaxKpa = 500;            explicit CoupledSetpointConsole(QWidget *parent = nullptr) : QWidget(parent) {            m_unitCombo = new QComboBox(this);            m_unitCombo->addItem(tr("Kilopascals (kPa)"), UnitKpa);            m_unitCombo->addItem(tr("Centibar (0.01 bar)"), UnitBarX100);                m_spin = new QSpinBox(this);            m_spin->setRange(kMinKpa, kMaxKpa);          m_spin->setKeyboardTracking(false); // Commit only on Enter/focus-out/step                m_slider = new QSlider(Qt::Horizontal, this);            m_slider->setRange(kMinKpa, kMaxKpa);            m_slider->setSingleStep(5);                m_dial = new QDial(this);            m_dial->setRange(kMinKpa, kMaxKpa);                m_lineEdit = new QLineEdit(this);            m_lineEdit->setValidator(new QIntValidator(kMinKpa, kMaxKpa, this));                m_utcFilter = new QDateTimeEdit(QDateTime::currentDateTimeUtc(), this);            m_utcFilter->setTimeZone(QTimeZone::UTC);            m_utcFilter->setDisplayFormat(QStringLiteral("yyyy-MM-dd HH:mm:ss 'UTC'"));                m_logView = new QPlainTextEdit(this);            m_logView->setReadOnly(true);            m_logView->setMaximumBlockCount(500); // Bounded O(1) ring eviction                auto *top = new QHBoxLayout();            top->addWidget(m_unitCombo);            top->addWidget(m_spin);            top->addWidget(m_slider);            top->addWidget(m_dial);            top->addWidget(m_lineEdit);            top->addWidget(m_utcFilter);                auto *root = new QVBoxLayout(this);            root->addLayout(top);            root->addWidget(m_logView);                applySetpoint(250, false);                connect(m_spin, &QSpinBox::valueChanged, this, [this](int v) { applySetpoint(v, true); });            connect(m_slider, &QSlider::valueChanged, this, [this](int v) { applySetpoint(v, true); });            connect(m_dial, &QDial::valueChanged, this, [this](int v) { applySetpoint(v, true); });            connect(m_lineEdit, &QLineEdit::editingFinished, this, [this] {                bool ok = false;                const int v = m_lineEdit->text().toInt(&ok);                if (ok) applySetpoint(v, true);            });        }        signals:        void setpointCommitted(int kpa, int unitEnum);        private:        void applySetpoint(int requestedKpa, bool emitBus) {            const int clamped = std::clamp(requestedKpa, kMinKpa, kMaxKpa);            if (clamped == m_kpa && emitBus) return;            m_kpa = clamped;          {                const QSignalBlocker bSpin(m_spin);                const QSignalBlocker bSlider(m_slider);                const QSignalBlocker bDial(m_dial);                const QSignalBlocker bEdit(m_lineEdit);                m_spin->setValue(m_kpa);                m_slider->setValue((m_kpa / 5) * 5);                m_dial->setValue(m_kpa);                m_lineEdit->setText(QString::number(m_kpa));            }            if (emitBus) {                const int unit = m_unitCombo->currentData().toInt();                m_logView->appendPlainText(QStringLiteral("COMMIT kpa=%1 unit=%2").arg(m_kpa).arg(unit));                emit setpointCommitted(m_kpa, unit);            }        }            int m_kpa = 250;        QComboBox *m_unitCombo = nullptr;        QSpinBox *m_spin = nullptr;        QSlider *m_slider = nullptr;        QDial *m_dial = nullptr;        QLineEdit *m_lineEdit = nullptr;        QDateTimeEdit *m_utcFilter = nullptr;        QPlainTextEdit *m_logView = nullptr;    };
  1. setKeyboardTracking(false) prevents partial keystrokes ('2', '25') from pulsing hardware setpoints before Enter.
  2. Four scoped QSignalBlocker instances silence coupled peer updates and restore prior blocked states before emit.
QValidator-QSignalBlocker(3qt) at a glance — GL-Q01
QValidator-QSignalBlocker(3qt) GL-Q01 Quick Reference QValidator-QSignalBlocker(3qt) NAME       QValidator, QSignalBlocker, QPlainTextEdit - input validation,       anti-echo sync, and bounded logs SYNOPSIS       const QSignalBlocker blocker(peerWidget); // RAII: saves & restores       prior signalsBlocked() spin->setKeyboardTracking(false); // emit       valueChanged only on commit or step combo->addItem(tr("kPa"), UnitKpa);       // read via combo->currentData().toInt()       log->setMaximumBlockCount(500); // evicts oldest paragraph block       automatically QVALIDATOR STATES       QValidator::Invalid Reject keystroke immediately; buffer unchanged       QValidator::Intermediate Permit prefix edit in buffer; suppress       editingFinished() QValidator::Acceptable In-range token; enables       editingFinished() / returnPressed() Kernel Systems Academy        Lesson 4.2        QValidator-QSignalBlocker(3qt) GL-Q01 quick reference · full manual page: man 3qt QValidator-QSignalBlocker 

Host C++20 Verifier for Range Validators, SignalBlocker Nesting, and Bounded Logs

Let us verify all three editor invariants in a self-contained ISO C++20 harness: prefix classification on [100, 500], anti-echo synchronization between an exact SpinBox and a 5-unit quantized Slider (including nested SignalBlocker preservation), and PlainLogRing eviction under a 4-block ceiling.

Examine RangeValidator::validate in verify.cpp: '2' and '25' have fewer digits than 500 (3 digits) so they classify as Intermediate, whereas '999' (> 500 at 3 digits), '-1' (lo >= 0), and '25a' classify immediately as Invalid.

learner@ksa: ~/gl-q01/m04-l02
learner@ksa:~/gl-q01/m04-l02$ bat -H 29 -H 72 verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cctype>    #include <cstdio>    #include <deque>    #include <functional>    #include <string>    #include <string_view>        enum class ValState { Invalid, Intermediate, Acceptable };        class RangeValidator {    public:        constexpr RangeValidator(int lo, int hi) noexcept : m_lo(lo), m_hi(hi) {}            ValState validate(std::string_view s) const noexcept {            if (s.empty()) return ValState::Intermediate;            std::size_t i = 0;            bool neg = false;            if (s[0] == '+' || s[0] == '-') {                neg = (s[0] == '-');                if ((neg && m_lo >= 0) || (!neg && m_hi < 0)) return ValState::Invalid;                ++i;                if (i == s.size()) return ValState::Intermediate;            }            long long v = 0;            for (; i < s.size(); ++i) {                const auto ch = static_cast<unsigned char>(s[i]);              if (!std::isdigit(ch)) return ValState::Invalid;                v = v * 10 + (ch - '0');                if (v > 1000000000LL) return ValState::Invalid;            }            const long long sv = neg ? -v : v;            if (sv >= m_lo && sv <= m_hi) return ValState::Acceptable;            if (!neg && m_hi >= 0 && sv < m_lo) {                int hi_digits = 0;                for (int t = m_hi; t > 0; t /= 10) ++hi_digits;                const int cur_digits = static_cast<int>(s.size() - (s[0] == '+' ? 1U : 0U));                if (cur_digits < hi_digits) return ValState::Intermediate;            }            return ValState::Invalid;        }        private:        int m_lo;        int m_hi;    };        class WidgetSignalNode {    public:        bool block_signals(bool b) noexcept {            const bool prev = m_blocked;            m_blocked = b;            return prev;        }        bool signals_blocked() const noexcept { return m_blocked; }        int value() const noexcept { return m_val; }            void set_value(int v) {            m_val = v;            if (!m_blocked && on_value_changed) {                ++emissions;                on_value_changed(v);            }        }            std::function<void(int)> on_value_changed;        int emissions = 0;        private:        int m_val = 0;      bool m_blocked = false;    };        class ScopedSignalBlocker {    public:        explicit ScopedSignalBlocker(WidgetSignalNode &w) noexcept            : m_w(w), m_prev(w.block_signals(true)) {}        ~ScopedSignalBlocker() { m_w.block_signals(m_prev); }        ScopedSignalBlocker(const ScopedSignalBlocker &) = delete;        ScopedSignalBlocker &operator=(const ScopedSignalBlocker &) = delete;        private:        WidgetSignalNode &m_w;        bool m_prev;    };        class PlainLogRing {    public:        explicit PlainLogRing(std::size_t max_blocks) noexcept : m_max(max_blocks) {}        void append_block(std::string line) {            if (m_blocks.size() == m_max) m_blocks.pop_front();            m_blocks.push_back(std::move(line));        }        std::size_t block_count() const noexcept { return m_blocks.size(); }        const std::string &oldest() const { return m_blocks.front(); }        private:        std::size_t m_max;        std::deque<std::string> m_blocks;    };        int main() {        constexpr RangeValidator val(100, 500);        assert(val.validate("") == ValState::Intermediate);        assert(val.validate("2") == ValState::Intermediate);        assert(val.validate("25") == ValState::Intermediate);        assert(val.validate("250") == ValState::Acceptable);        assert(val.validate("500") == ValState::Acceptable);        assert(val.validate("600") == ValState::Invalid);        assert(val.validate("-5") == ValState::Invalid);        assert(val.validate("25x") == ValState::Invalid);            WidgetSignalNode spin;        WidgetSignalNode slider;        int bus_frames = 0;            spin.on_value_changed = [&](int v) {            const ScopedSignalBlocker guard(slider);            slider.set_value((v / 5) * 5);            ++bus_frames;        };        slider.on_value_changed = [&](int v) {            const ScopedSignalBlocker guard(spin);            spin.set_value(v);            ++bus_frames;        };            spin.set_value(243);        assert(spin.value() == 243 && slider.value() == 240);        assert(spin.emissions == 1 && slider.emissions == 0 && bus_frames == 1);            slider.block_signals(true);        {            const ScopedSignalBlocker nested(slider);            slider.set_value(310);        }        assert(slider.signals_blocked());            PlainLogRing log(4);        for (int i = 1; i <= 7; ++i) log.append_block("seq_" + std::to_string(i));        assert(log.block_count() == 4 && log.oldest() == "seq_4");            std::printf("editors_audit: spin=%d slider=%d commits=%d nested_kept=%d log_blocks=%zu oldest=%s\n",                    spin.value(), slider.value(), bus_frames,                    slider.signals_blocked() ? 1 : 0,                    log.block_count(), log.oldest().c_str());        return 0;    }
  1. Prefix strings shorter than m_hi's digit count return Intermediate so multi-keystroke entry reaches [100, 500].
  2. ScopedSignalBlocker saves block_signals(true)'s return value so nested callers never clobber an outer blocked state.

Inspecting Anti-Echo Counts, Validator Transitions, and Log Eviction

Run ./verify and confirm spin=243 slider=240 commits=1 nested_kept=1 log_blocks=4 oldest=seq_4. Setting spin to 243 quantized slider to 240 without firing slider.on_value_changed back into spin, emitted exactly 1 outbound bus commit, and preserved slider.signals_blocked() == true across the nested scope.

Meanwhile, appending 7 lines into PlainLogRing(4) capped memory at 4 blocks with seq_4 at the head—mirroring QPlainTextEdit::setMaximumBlockCount(4) on long-running embedded diagnostic consoles.

learner@ksa: ~/gl-q01/m04-l02
learner@ksa:~/gl-q01/m04-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m04-l02./verifyeditors_audit: spin=243 slider=310 commits=1 nested_kept=1 log_blocks=4 oldest=seq_4learner@ksa:~/gl-q01/m04-l02
strace — learner@ksa: ~/gl-q01/m04-l02
learner@ksa:~/gl-q01/m04-l02strace -e trace=write,exit_group ./verifywrite(1, "editors_audit: spin=243 slider=3"..., 85) = 85exit_group(0)                           = ?+++ exited with 0 +++

Field Pitfalls in Coupled Editors, Rich-Text Logs, and Locale Strings

Validating prefixes cleanly, blocking programmatic echo via RAII, and bounding log document growth keep data-entry panels deterministic across weeks of uptime. Next, Lesson 4.3 examines how Qt's geometry solvers position these editors across diverse screen resolutions without magic pixel coordinates.

Keep host-versus-target scope explicit: host C++20 tests verify validator automata and signal-graph invariants, whereas virtual on-screen keyboard (QtVirtualKeyboard) focus geometry and font metrics must be checked on the target panel.

Streaming Continuous Serial or CAN Logs into QTextEdit Without Block Caps:

  • Symptom: After 6 hours of 100 Hz CAN traffic, HMI resident memory climbs past 300 MiB and every append freezes the GUI thread for 40 ms.
  • Root Cause: QTextEdit builds an unbounded rich-text HTML/CSS QTextDocument layout tree and re-paginates paragraphs on append.
  • Fix: Replace QTextEdit with read-only QPlainTextEdit and call setMaximumBlockCount(500) to bound RAM in O(1) time.

Matching QComboBox::currentText() Against English Literals:

  • Symptom: Switching the HMI locale to German ('Kilopascal' or 'Aus') silently falls through unit-conversion branches and sends zeroed setpoints.
  • Root Cause: currentText() returns the user-visible tr() translated string rather than a language-invariant identifier.
  • Fix: Store enum constants via combo->addItem(tr("..."), UnitKpa) and branch exclusively on combo->currentData().toInt().

Guided Practice

Extend RangeValidator in verify.cpp to support signed negative temperature ranges [-40, -10] degrees Celsius. Test "", "-", "-2" (Acceptable or Intermediate? Careful: -2 > -10, yet typing '-', '2', '5' must pass through "-2" as Intermediate on the way to "-25"!) and verify both "-2" (Intermediate) and "-25" (Acceptable).

Independent Practice

Build a fixed-point CentibarSpinModel storing pressure in int32_t hundredths of a bar ([100, 500] -> 1.00 .. 5.00 bar) with exact string formatting and parsing ("2.45" <-> 245), proving that 10,000 consecutive +0.01 increments land at exact 10245 with zero floating-point rounding drift.

Verification Checks

quiz · 1 of 3

With QIntValidator(100, 500) attached to a QLineEdit, what does validate("25", pos) return while the operator types '2', '5', '0'?

quiz · 2 of 3

Why is const QSignalBlocker b(widget); strictly safer than widget->blockSignals(true); ... widget->blockSignals(false);?

quiz · 3 of 3

Which widget and configuration should display a continuous 200 lines/sec diagnostic UART trace on a 512 MiB embedded Linux panel?

Key takeaways

  • QValidator classifies input strings into Invalid (rejected immediately), Intermediate (permitted while typing toward a valid value while suppressing editingFinished()), and Acceptable (eligible to commit).
  • Stack-scoped QSignalBlocker suppresses intermediate signal emissions during programmatic peer-widget updates and restores the widget's prior signalsBlocked() boolean on scope exit.
  • QPlainTextEdit with setMaximumBlockCount() stores line-oriented logs in bounded plain-text blocks (O(1) eviction), whereas QTextEdit and QTextBrowser maintain a full rich-text QTextDocument layout tree.
  • Attaching typed QVariant user data to QComboBox::addItem(), setting QSpinBox::setKeyboardTracking(false), and pinning QDateTimeEdit to QTimeZone::UTC prevent locale drift and half-typed setpoint spikes.
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure