Custom QPainter Gauges, Premultiplied ARGB32 & Real-Time QtCharts

Render tear-free 60 Hz radial gauges in paintEvent using dirty clipRegion() bounds and Format_ARGB32_Premultiplied caches, and stream real-time QtCharts waveforms via batched replace().

35 minfree previewLinux 6.12→ module 6 lab
What you'll learn
  • Implement custom QWidget::paintEvent(QPaintEvent *) gauges using logical translate/scale transforms, ev->region() clipping, and update() coalescing.
  • Prove Porter-Duff SourceOver compositing arithmetic on QImage::Format_ARGB32_Premultiplied static dial caches without per-pixel alpha division.
  • Eliminate GUI-thread stalls in real-time QtCharts (QChart, QLineSeries, QValueAxis) by replacing per-sample append() calls with ring-buffered replace(QList<QPointF>).

Premultiplied Alpha Physics and the paintEvent Backing-Store Contract

In QtWidgets, every top-level window owns a software double-buffered backing store managed by QWidgetRepaintManager. You NEVER construct QPainter(this) inside a telemetry slot or call synchronous repaint() in a loop; instead, your setter updates m_kpa and calls update(), posting a coalesced UpdateRequest so paintEvent(QPaintEvent *ev) runs once per display frame with ev->region() bounding the exact dirty area.

When caching static bezel rings and tick marks into an off-screen QImage, always choose QImage::Format_ARGB32_Premultiplied over straight Format_ARGB32. Straight alpha blending must multiply source and destination channels by alpha AND divide by output alpha on every pixel! Premultiplied alpha stores (R*A/255, G*A/255, B*A/255) upfront, reducing Porter-Duff SourceOver to out = src + (dst * (255 - sa) + 127) / 255—pure integer multiplies and shifts with zero division!

Inside paintEvent, normalize DPI and resize math by translating (width()/2.0, height()/2.0) and scaling (side/200.0, side/200.0) so gauge geometry lives in a crisp [-100, +100] coordinate system—remembering that QPainter::drawArc integer angles are measured in 1/16th of a degree (360 * 16 = 5760)!

fig_m06_l02_a.svg — Eliminating per-pixel division and per-sample chart…

Figure 6.2a. Eliminating per-pixel division and per-sample chart re-layout on embedded Linux HMIs.

mental model: Caching static gauge ticks into a Format_ARGB32_Premultiplied QImage and batching QLineSeries::replace() works like printing an oscilloscope's graticule grid onto the glass bezel once and sweeping one complete phosphor trace per frame—instead of re-engraving the glass ruler every millisecond a sample arrives.

Where it stops working: Etched glass consumes zero RAM, whereas each cached 400x400 ARGB32_Premultiplied QImage occupies 640 KiB (400 * 400 * 4 bytes)—so cache shared dial backgrounds per distinct size rather than duplicating hundreds of megapixel bitmaps.

definition ( & QLineSeries::replace()): In QImage::Format_ARGB32_Premultiplied, a pixel with straight color (A, R, G, B) stores (A, R*A/255, G*A/255, B*A/255) (invariant R', G', B' <= A), matching Qt's software rasterizer natively with zero format conversion or alpha division. In QtCharts, QXYSeries::replace(const QList<QPointF> &) swaps the entire vertex vector and emits a single pointsReplaced() notification instead of N pointAdded(int) signals.

ast_m06_l02.svg — Paint in paintEvent via update(), cache…step 1/4
  1. Step 1. Guard setters for value changes and call asynchronous update() so Qt coalesces dirty regions.
  2. Step 2. Pre-render static bezel and tick geometry into QImage::Format_ARGB32_Premultiplied on resize.
  3. Step 3. Normalize coordinates via translate/scale and multiply integer drawArc angles by 16 (1/16th degree).
  4. Step 4. Update real-time QLineSeries traces once per frame via replace(QList<QPointF>) instead of per-point append().

Figure 6.2b. Paint in paintEvent via update(), cache ARGB32_Premultiplied, and batch series->replace().

High-Rate Real-Time Waveforms in QtCharts: Why replace Beats append

Alongside radial gauges, industrial HMIs plot rolling 512-sample pressure and current waveforms using QtCharts (QChart, QChartView, QLineSeries, and explicit QValueAxis bounds). The single most common QtCharts performance bug on embedded ARMv7-A Cortex-A7 boards is calling m_series->append(t, y) (and m_series->remove(0)) directly inside a 1 kHz sensor callback!

Every single append(x, y) emits pointAdded(int), marks the QGraphicsScene dirty, and triggers chart geometry bookkeeping—doing that 1,000 times per second starves the GUI event loop! Instead, ingest incoming samples into a plain C++ ring buffer, and on a 33 ms (30 Hz) UI frame timer build or rotate a QList<QPointF> buffer and call m_series->replace(m_framePoints).

Pair replace() with three QChart hardening settings: call chart->setAnimationOptions(QChart::NoAnimation) (animations interpolate every vertex on CPU!), attach fixed QValueAxis ranges (axisY->setRange(0, 500)) rather than auto-scaling every frame, and call chart->legend()->hide() on compact strip charts.

fig_m06_l02_b.svg — Bit-level premultiplied ARGB32 layout and QtCharts…

Figure 6.2b. Bit-level premultiplied ARGB32 layout and QtCharts real-time series architecture.

Rendering DecisionHigh-Overhead Naive ChoiceProduction Qt 6 ChoiceMeasured Engineering Impact
Off-screen QImage cache formatQImage::Format_ARGB32 (straight)QImage::Format_ARGB32_PremultipliedEliminates format conversion & per-pixel alpha division
Scheduling widget redrawsDirect repaint() per packetValue-guarded update() + ev->region()Coalesces bursts into 1 VSync-paced paintEvent
Static gauge bezel & 60 ticksRe-stroke sin/cos ticks every frameBlit cached QImage rebuilt only in resizeEventDrops per-frame draw calls to dynamic arc + needle only
QtCharts 1 kHz waveformPer-sample series->append(x, y)Ring buffer + 30 Hz series->replace(points)1 pointsReplaced() signal/frame instead of 1,000/s
learner@ksa: ~/gl-q01/m06-l02
learner@ksa:~/gl-q01/m06-l02$ bat -H 58 -H 114 gauge_and_chart_panel.cpp File: gauge_and_chart_panel.cpp    #include <QtCharts/QChart>    #include <QtCharts/QChartView>    #include <QtCharts/QLineSeries>    #include <QtCharts/QValueAxis>    #include <QHBoxLayout>    #include <QImage>    #include <QList>    #include <QPaintEvent>    #include <QPainter>    #include <QPointF>    #include <QWidget>    #include <algorithm>        class RadialPressureGauge final : public QWidget {        Q_OBJECT    public:        explicit RadialPressureGauge(QWidget *parent = nullptr) : QWidget(parent) {}        QSize minimumSizeHint() const override { return {120, 120}; }        QSize sizeHint() const override { return {220, 220}; }            void setPressureKpa(int kpa) {            const int clamped = std::clamp(kpa, 0, 500);            if (clamped == m_kpa) return;            const bool wasHigh = (m_kpa >= m_alarmKpa);            m_kpa = clamped;            if ((m_kpa >= m_alarmKpa) && !wasHigh) emit alarmTriggered(m_kpa);            update(); // Asynchronous coalesced repaint        }        signals:        void alarmTriggered(int kpa);        protected:        void resizeEvent(QResizeEvent *ev) override {            m_dialCache = QImage();            QWidget::resizeEvent(ev);        }            void paintEvent(QPaintEvent *ev) override {            if (m_dialCache.isNull() || m_dialCache.size() != size()) rebuildCache();            QPainter p(this);            p.setClipRegion(ev->region()); // Respect dirty-region clip!            p.drawImage(0, 0, m_dialCache);                p.setRenderHint(QPainter::Antialiasing, true);            const double side = std::min(width(), height());            p.translate(width() / 2.0, height() / 2.0);            p.scale(side / 200.0, side / 200.0);                const QColor col = (m_kpa >= m_alarmKpa) ? QColor(0xDC, 0x26, 0x26) : QColor(0x0E, 0xA5, 0xE9);            p.setPen(QPen(col, 10.0, Qt::SolidLine, Qt::FlatCap));            const int span16 = static_cast<int>((-240.0 * m_kpa / 500.0) * 16.0);            p.drawArc(QRectF(-76.0, -76.0, 152.0, 152.0), 210 * 16, span16);        }        private:        void rebuildCache() {          m_dialCache = QImage(size(), QImage::Format_ARGB32_Premultiplied);            m_dialCache.fill(Qt::transparent);            QPainter cp(&m_dialCache);            cp.setRenderHint(QPainter::Antialiasing, true);            const double side = std::min(width(), height());            cp.translate(width() / 2.0, height() / 2.0);            cp.scale(side / 200.0, side / 200.0);            cp.setPen(QPen(QColor(0x33, 0x41, 0x55), 10.0));            cp.drawArc(QRectF(-76.0, -76.0, 152.0, 152.0), 210 * 16, -240 * 16);        }            int m_kpa = 0;        int m_alarmKpa = 420;        QImage m_dialCache;    };        class BatchedWaveformStrip final : public QWidget {        Q_OBJECT    public:        static constexpr int kWindow = 256;            explicit BatchedWaveformStrip(QWidget *parent = nullptr) : QWidget(parent) {            m_series = new QLineSeries(this);            auto *chart = new QChart();            chart->setAnimationOptions(QChart::NoAnimation);            chart->legend()->hide();            chart->addSeries(m_series);                auto *axX = new QValueAxis(chart);            axX->setRange(0.0, kWindow - 1);            auto *axY = new QValueAxis(chart);            axY->setRange(0.0, 500.0);            chart->addAxis(axX, Qt::AlignBottom);            chart->addAxis(axY, Qt::AlignLeft);            m_series->attachAxis(axX);            m_series->attachAxis(axY);                m_points.resize(kWindow);            for (int i = 0; i < kWindow; ++i) m_points[i] = QPointF(i, 0.0);                auto *lay = new QHBoxLayout(this);            lay->setContentsMargins(0, 0, 0, 0);            lay->addWidget(new QChartView(chart, this));        }            void pushSampleRing(double kpa) {            m_ring[static_cast<std::size_t>(m_head)] = kpa;            m_head = (m_head + 1) % kWindow;        }            void flushFrame30Hz() {            for (int i = 0; i < kWindow; ++i) {                const double y = m_ring[static_cast<std::size_t>((m_head + i) % kWindow)];                m_points[i].setY(y);            }            m_series->replace(m_points); // Single pointsReplaced() emission!      }        private:        QLineSeries *m_series = nullptr;        QList<QPointF> m_points;        double m_ring[kWindow]{};        int m_head = 0;    };
  1. Static bezel ticks rasterize once into QImage::Format_ARGB32_Premultiplied on resize, avoiding per-frame trig.
  2. flushFrame30Hz() swaps all 256 ring samples via m_series->replace(m_points) in a single chart notification.
QPainter-QtCharts(3qt) at a glance — GL-Q01
QPainter-QtCharts(3qt)      GL-Q01 Quick Reference      QPainter-QtCharts(3qt) NAME       QPainter, QImage::Format_ARGB32_Premultiplied, QLineSeries - 60 Hz       gauges & batched charts SYNOPSIS       QImage cache(size(), QImage::Format_ARGB32_Premultiplied);       cache.fill(Qt::transparent);       painter.setClipRegion(event->region());       painter.drawArc(rectF, startDeg * 16, spanDeg * 16);       lineSeries->replace(framePointsList);   // 1 signal per frame vs N append() signals        PERFORMANCE & CORRECTNESS RULES 1. Paint QWidgets ONLY inside       paintEvent(QPaintEvent *); trigger redraws via update(). 2.       Premultiplied ARGB32 requires R', G', B' <= A; clear new QImages before       drawing. 3. Set QChart::NoAnimation and batch streaming waveforms via       QXYSeries::replace(). Kernel Systems Academy            Lesson 6.2            QPainter-QtCharts(3qt) GL-Q01 quick reference · full manual page: man 3qt QPainter-QtCharts 

Host C++20 Verifier & Benchmark for Premultiplied ARGB32 and Batched Series Replace

In verify.cpp, we verify three exact quantitative mechanisms: premultiplied ARGB32 Porter-Duff SourceOver compositing inside a {20, 20, 60, 60} dirty clip rectangle, radial midpoint needle projection (250 kPa -> 90 deg -> (50, 15)), and a CLOCK_MONOTONIC comparison between 512 per-point append_single operations (recomputing bounds + notifying per point) versus one replace_batch pass!

Check both pixel invariants and notification counts: pixels outside the dirty clip remain 0xFF102030, blended channels satisfy c <= a, and replace_batch reduces layout notifications from 512 to 1.

learner@ksa: ~/gl-q01/m06-l02
learner@ksa:~/gl-q01/m06-l02$ bat -H 27 -H 71 verify.cpp File: verify.cpp    #include <algorithm>    #include <array>    #include <cassert>    #include <cmath>    #include <cstdint>    #include <cstdio>    #include <ctime>    #include <numbers>    #include <vector>        struct Rect {        int x, y, w, h;        constexpr bool contains(int px, int py) const noexcept {            return px >= x && px < (x + w) && py >= y && py < (y + h);        }    };        static constexpr std::uint32_t pack_premul(std::uint8_t a, std::uint8_t r,                                               std::uint8_t g, std::uint8_t b) noexcept {        const std::uint32_t pr = (static_cast<std::uint32_t>(r) * a + 127U) / 255U;        const std::uint32_t pg = (static_cast<std::uint32_t>(g) * a + 127U) / 255U;        const std::uint32_t pb = (static_cast<std::uint32_t>(b) * a + 127U) / 255U;        return (static_cast<std::uint32_t>(a) << 24U) | (pr << 16U) | (pg << 8U) | pb;    }        static constexpr std::uint32_t blend_over(std::uint32_t src, std::uint32_t dst) noexcept {      const std::uint32_t sa = (src >> 24U) & 0xFFU;        if (sa == 255U) return src;        if (sa == 0U) return dst;        const std::uint32_t inv = 255U - sa;        auto ch = [inv](std::uint32_t s, std::uint32_t d, unsigned sh) {            const std::uint32_t sc = (s >> sh) & 0xFFU;            const std::uint32_t dc = (d >> sh) & 0xFFU;            return std::min(255U, sc + (dc * inv + 127U) / 255U);        };        return (ch(src, dst, 24U) << 24U) | (ch(src, dst, 16U) << 16U) |               (ch(src, dst, 8U) << 8U) | ch(src, dst, 0U);    }        class PremulSurface {    public:        PremulSurface(int w, int h, std::uint32_t bg)            : m_w(w), m_h(h), m_clip{0, 0, w, h}, m_px(static_cast<std::size_t>(w * h), bg) {}        void set_clip(Rect c) noexcept { m_clip = c; }        void blend_hline(int x0, int x1, int y, std::uint32_t premul) noexcept {            for (int x = x0; x <= x1; ++x) {                if (x >= 0 && x < m_w && y >= 0 && y < m_h && m_clip.contains(x, y)) {                    auto &d = m_px[static_cast<std::size_t>(y * m_w + x)];                    d = blend_over(premul, d);                }            }        }        std::uint32_t pixel(int x, int y) const noexcept {            return m_px[static_cast<std::size_t>(y * m_w + x)];        }        private:        int m_w, m_h;        Rect m_clip;        std::vector<std::uint32_t> m_px;    };        class MockLineSeries {    public:        void append_single(double x, double y) {            if (m_pts.size() == 512U) m_pts.erase(m_pts.begin());            m_pts.push_back({x, y});            recompute_scene_bounds(); // Per-point chart overhead!        }        void replace_batch(const std::vector<std::pair<double, double>> &batch) {          m_pts = batch;            recompute_scene_bounds(); // Single pass per frame!        }        int layout_passes = 0;        double y_span = 0.0;        private:        void recompute_scene_bounds() noexcept {            ++layout_passes;            double lo = 1e9, hi = -1e9;            for (const auto &p : m_pts) {                lo = std::min(lo, p.second);                hi = std::max(hi, p.second);            }            y_span = hi - lo;        }        std::vector<std::pair<double, double>> m_pts;    };        static std::uint64_t mono_ns() noexcept {        timespec ts{};        clock_gettime(CLOCK_MONOTONIC, &ts);        return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL +               static_cast<std::uint64_t>(ts.tv_nsec);    }        int main() {        constexpr std::uint32_t bg = pack_premul(255, 16, 32, 48);        PremulSurface surf(100, 100, bg);        surf.set_clip({20, 20, 60, 60});        surf.blend_hline(50, 95, 50, pack_premul(128, 220, 38, 38));            const std::uint32_t inside = surf.pixel(60, 50);        const std::uint32_t clipped = surf.pixel(85, 50);        assert(clipped == bg && ((inside >> 24U) & 0xFFU) == 255U);            const double rad = (210.0 - 240.0 * 250.0 / 500.0) * std::numbers::pi / 180.0;        const int tip_x = 50 + static_cast<int>(std::lround(35.0 * std::cos(rad)));        const int tip_y = 50 - static_cast<int>(std::lround(35.0 * std::sin(rad)));        assert(tip_x == 50 && tip_y == 15);            std::vector<std::pair<double, double>> frame(512);        for (int i = 0; i < 512; ++i) frame[static_cast<std::size_t>(i)] = {double(i), double(i % 400)};            MockLineSeries s_append, s_replace;        const std::uint64_t t0 = mono_ns();        for (const auto &pt : frame) s_append.append_single(pt.first, pt.second);        const std::uint64_t append_ns = mono_ns() - t0;            const std::uint64_t t1 = mono_ns();        s_replace.replace_batch(frame);        const std::uint64_t replace_ns = mono_ns() - t1;            assert(s_append.layout_passes == 512 && s_replace.layout_passes == 1);        assert(s_append.y_span == s_replace.y_span);            std::printf("render_audit: inside=0x%08X clipped=0x%08X tip=(%d,%d) append_ns=%llu replace_ns=%llu\n",                    inside, clipped, tip_x, tip_y,                    static_cast<unsigned long long>(append_ns),                    static_cast<unsigned long long>(replace_ns));        return 0;    }
  1. Porter-Duff SourceOver on premultiplied pixels blends in pure integer shift/multiply math without division.
  2. replace_batch swaps all 512 points and triggers 1 scene bounds pass instead of 512 per-point passes.

Verifying ARGB32 Blending, Clip Isolation, and QtCharts Batch Speedup

Confirm ./verify outputs inside=0xFF772326 clipped=0xFF102030 tip=(50,15) along with append_ns more than 100x slower than replace_ns! Pixels at (85, 50) stayed untouched outside {20, 20, 60, 60}, 250 kPa pointed straight to (50, 15), and batched replace cut layout passes from 512 to 1.

Next, Lesson 6.3 automates verification of custom gauges, signals, and interactive widgets inside headless Linux CI containers using QTest and QSignalSpy.

learner@ksa: ~/gl-q01/m06-l02
learner@ksa:~/gl-q01/m06-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m06-l02./verifyrender_audit: inside=0xFF76232B clipped=0xFF102030 tip=(50,15) append_ns=1122140 replace_ns=16678learner@ksa:~/gl-q01/m06-l02
strace — learner@ksa: ~/gl-q01/m06-l02
learner@ksa:~/gl-q01/m06-l02strace -e trace=write,exit_group ./verifywrite(1, "render_audit: inside=0xFF76232B "..., 98) = 98exit_group(0)                           = ?+++ exited with 0 +++

Uninitialized QImage Garbage, 1/16th-Degree Arc Bugs, and Chart Animations

Premultiplied ARGB32 static layer caching and ring-buffered QLineSeries::replace() allow CPU-rendered QtWidgets dashboards to sustain crisp 60 Hz instrumentation without requiring a GPU shader pipeline.

Remember the hardware boundary: host benchmarks prove compositing and batching complexity, whereas display tearing and DRM/KMS page-flip latency must be verified on the target LCD controller.

Forgetting m_dialCache.fill(Qt::transparent) After Constructing QImage:

  • Symptom: Custom gauge renders random colored static noise and corrupted text streaks behind the dial arc on startup and resize.
  • Root Cause: QImage(size, format) allocates an uninitialized heap pixel buffer containing leftover allocator bytes.
  • Fix: Call image.fill(Qt::transparent) (0x00000000 in premultiplied ARGB32) immediately before opening QPainter(&image).

Passing Whole Degrees Instead of 1/16th Degrees to QPainter::drawArc:

  • Symptom: Gauge arc intended to sweep 240 degrees renders as a tiny 15-degree tick mark near 3 o'clock.
  • Root Cause: QPainter::drawArc, drawPie, and drawChord expect integer angles in 1/16th-degree increments (5760 == 360 deg).
  • Fix: Multiply both startAngle and spanAngle by 16 (e.g., 210 * 16 and -240 * 16 for a clockwise 240-degree sweep).

Guided Practice

Add a channel-invariant verifier is_valid_premul(uint32_t px) to verify.cpp checking that pr <= a, pg <= a, and pb <= a for every pixel across surf after compositing three overlapping translucent strokes (alpha = 64, 128, 200), proving Porter-Duff SourceOver preserves premultiplied invariants.

Independent Practice

Write a fixed-capacity power-of-two WaveformRing<512> in C++20 supporting push_isr_sample(float) and copy_chronological(std::span<Point2D, 512>) with zero heap allocations on the 30 Hz render path.

Verification Checks

quiz · 1 of 3

Why does Qt's raster paint engine strongly prefer QImage::Format_ARGB32_Premultiplied over straight QImage::Format_ARGB32 for off-screen QPainter caches?

quiz · 2 of 3

What does painter.drawArc(rect, 90, 180) actually draw on screen?

quiz · 3 of 3

A 1 kHz ADC stream feeds a QtCharts QLineSeries strip chart on an embedded panel, pegging CPU usage at 100%. Which change fixes the bottleneck?

Key takeaways

  • All QWidget drawing must execute inside paintEvent(QPaintEvent *) (scheduled asynchronously via update()), honoring event->region() dirty clip bounds on the window backing store.
  • QImage::Format_ARGB32_Premultiplied pre-scales RGB channels by alpha / 255, letting QPainter Porter-Duff SourceOver blend out = src + dst * (255 - a) / 255 without per-pixel division.
  • Caching static gauge bezels and tick marks into a Format_ARGB32_Premultiplied QImage on resizeEvent avoids repeating trigonometric tick strokes on every 60 Hz needle update.
  • In QtCharts, calling QLineSeries::append(x, y) at 1 kHz triggers 1,000 per-point signal/layout passes per second, whereas buffering samples and calling series->replace(points) at 30 Hz emits once per frame.
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure