Event Loops, postEvent vs sendEvent & QObject::eventFilter

Trace QEvent delivery from QCoreApplication::exec() through LIFO eventFilter hooks to QObject::event, respecting heap-versus-stack event ownership and UpdateRequest coalescing.

30 minfree previewLinux 6.12→ module 3 lab
What you'll learn
  • Enforce strict stack allocation for synchronous sendEvent calls and new heap transfer for asynchronous postEvent calls.
  • Implement a central LIFO QObject::eventFilter safety interlock that consumes prohibited operator input (return true) while forwarding benign events (return false).
  • Contrast QWidget::update() posted repaint coalescing against synchronous QWidget::repaint() CPU thrashing.

Inside QCoreApplication::exec(): Multiplexing, Ownership & Interception

When main() enters app.exec(), Qt's thread-local QEventDispatcherUNIX (or Glib) sleeps inside ppoll() / epoll_wait() monitoring Wayland or evdev input descriptors, socket notifiers, an internal wake-up eventfd, and the next timer deadline—burning 0% CPU while idle. Events enter QCoreApplication::notify(receiver, event) down two very different roads: sendEvent invokes notify() synchronously right now on your current stack frame, whereas postEvent locks the receiver thread's mutex, appends the QEvent * to a priority queue, pokes eventfd, and deletes the event after delivery!

Before notify() ever calls receiver->event(ev), it walks every watcher attached via receiver->installEventFilter(watcher) in reverse installation order (LIFO). That single hook lets an industrial safety controller block axis-jogging keys across twenty spinboxes and buttons when an enclosure door opens—without subclassing a single widget!

fig_m03_l02_a.svg — postEvent takes heap ownership and compresses repaints;…

Figure 3.2a. postEvent takes heap ownership and compresses repaints; sendEvent borrows stack events synchronously; LIFO filters consume on true.

mental model: sendEvent works like handing a reusable laminated checklist directly to a technician and taking it back as soon as they initial it; postEvent drops a single-use paper work order into a pneumatic tube inbox that the dispatch desk owns, merges duplicate repaint slips, and feeds straight into a shredder (delete) once completed.

Where it stops working: An eventFilter watcher MUST live on the same thread as the watched QObject: Qt asserts and refuses cross-thread installEventFilter calls because notify() invokes watcher->eventFilter() synchronously without locking across threads.

definition (QCoreApplication::postEvent, sendEvent, and eventFilter): QCoreApplication::sendEvent(QObject *receiver, QEvent *event) is a synchronous thin wrapper around notify() that borrows caller-owned (typically stack) *event and returns bool. QCoreApplication::postEvent(QObject *receiver, QEvent *event, int priority) is thread-safe, takes immediate ownership of heap-allocated event, inserts it by descending priority (High=1, Normal=0, Low=-1 for UpdateRequest), and deletes event after dispatch. QObject::eventFilter intercepts every event addressed to watched in LIFO registration order prior to watched->event().

ast_m03_l02.svg — Heap-allocate for postEvent, stack-allocate for…step 1/4
  1. Step 1. Use new QEvent exclusively for postEvent and stack QEvent variables for synchronous sendEvent.
  2. Step 2. Call QWidget::update() inside data slots so Qt coalesces multiple dirty regions into one QPaintEvent.
  3. Step 3. Remember LIFO ordering when stacking audit loggers and safety interlock filters on one widget.
  4. Step 4. End every eventFilter override with return BaseClass::eventFilter(watched, event) (false).

Figure 3.2b. Heap-allocate for postEvent, stack-allocate for sendEvent, and end eventFilter with false.

Priority Queue Ordering, Repaint Compression & LIFO Filter Mechanics

Look inside safety_event_filter.cpp below. JogInterlockFilter watches multiple motion controls on a CNC pendant. When m_guardClosed == false and a QEvent::KeyPress arrives for Qt::Key_Up or Qt::Key_Down, eventFilter emits motionBlocked for the status bar and returns true—halting propagation before ANY earlier-installed filter or watched->event() can move the spindle. For every other event (QEvent::Paint, QEvent::FocusIn, Qt::Key_Escape), QObject::eventFilter returns false so rendering and emergency cancel keys behave normally.

Examine schedulePanelRefresh and injectSyncSelfTest below the class as well. Why does QWidget::update() post QEvent::UpdateRequest at Qt::LowEventPriority (-1)? Because draining all NormalEventPriority (0) socket, timer, and input events FIRST lets fifty incoming telemetry updates mutate widget properties in nanoseconds before Qt executes one single expensive QPainter raster pass at the end of the turn!

fig_m03_l02_b.svg — Scheduling UpdateRequest at LowEventPriority (-1)…

Figure 3.2b. Scheduling UpdateRequest at LowEventPriority (-1) guarantees all pending data mutations settle before a single paintEvent runs.

Dispatch / Redraw CallExecution TimingEvent AllocationCoalescing & Stack Safety
QCoreApplication::sendEventImmediate synchronous callStack QKeyEvent ev(...);Zero coalescing; re-enters immediately on current stack
QCoreApplication::postEventAsynchronous on target loop turnHeap new CustomEvent(...)Thread-safe; queue deletes event after notify()
QWidget::update()Deferred LowEventPriority (-1)Internal compressed UpdateRequest100 calls in one turn merge into 1 paintEvent
QWidget::repaint()Immediate synchronous raster passDirect stack QPaintEventBypasses compression; stalls slot and risks recursion
learner@ksa: ~/gl-q01/m03-l02
learner@ksa:~/gl-q01/m03-l02$ bat -H 22 -H 25 safety_event_filter.cpp File: safety_event_filter.cpp    #include <QCoreApplication>    #include <QEvent>    #include <QKeyEvent>    #include <QObject>    #include <QWidget>        namespace hmi {        class JogInterlockFilter final : public QObject {        Q_OBJECT    public:        explicit JogInterlockFilter(QObject *parent = nullptr) : QObject(parent) {}            void setGuardClosed(bool closed) noexcept { m_guardClosed = closed; }        protected:        bool eventFilter(QObject *watched, QEvent *event) override {            if (!m_guardClosed && event->type() == QEvent::KeyPress) {                const auto *ke = static_cast<const QKeyEvent *>(event);                if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down) {                    emit motionBlocked(watched, ke->key());                  return true; // Consumed: watched->event() never executes!                }            }          return QObject::eventFilter(watched, event); // Returns false: forward!        }        signals:        void motionBlocked(QObject *control, int qtKey);        private:        bool m_guardClosed = false;    };        inline void postDeferredRefresh(QObject *panel) {        // Heap-allocated: postEvent takes ownership and deletes after dispatch        QCoreApplication::postEvent(            panel, new QEvent(QEvent::UpdateRequest), Qt::LowEventPriority);    }        inline bool sendSyncEscapeKey(QWidget *dialog) {        // Stack-allocated: sendEvent borrows &esc synchronously without deleting        QKeyEvent esc(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier);        return QCoreApplication::sendEvent(dialog, &esc);    }        } // namespace hmi
  1. Returning true aborts event delivery immediately so neither earlier filters nor watched->keyPressEvent() run.
  2. Delegating unhandled events to QObject::eventFilter returns false so QEvent::Paint and Focus events reach watched.
QCoreApplication-events(3qt) at a glance — GL-Q01
QCoreApplication-events(3qt) GL-Q01 Quick Reference QCoreApplication-events(3qt) NAME       sendEvent, postEvent, installEventFilter - Qt 6 event delivery &       interception SYNOPSIS       static bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event);       static void QCoreApplication::postEvent(QObject *receiver, QEvent *event,                                            int priority = Qt::NormalEventPriority);       void QObject::installEventFilter(QObject *filterObj);       virtual bool QObject::eventFilter(QObject *watched, QEvent *event); CONTRACT       - sendEvent: synchronous; caller owns *event (allocate on stack). -       postEvent: asynchronous & thread-safe; queue owns *event (allocate via       new). - eventFilter: runs in LIFO installation order; true consumes,       false forwards. Kernel Systems Academy         Lesson 3.2         QCoreApplication-events(3qt) GL-Q01 quick reference · full manual page: man 3qt QCoreApplication-events 

Verifying Priority Draining, Paint Compression & LIFO Filters in C++20

In verify.cpp, we build a deterministic C++20 EventDispatcher modeling priority-sorted post_event(std::unique_ptr<Ev>) ownership, per-widget UpdateRequest compression, synchronous stack send_event(Ev &), and LIFO install_event_filter chains.

Inspect main(): audit is installed first and door is installed second (LIFO). While door.closed == false, sending Key_Up (100) hits door first, increments door.blocked, and returns true before audit or jog_btn ever sees the key! Posting 6 UpdateRequest events alongside a high-priority key drains KeyPress first and coalesces all 6 updates into 1 paint pass.

learner@ksa: ~/gl-q01/m03-l02
learner@ksa:~/gl-q01/m03-l02$ bat -H 60 -H 70 verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cstdio>    #include <memory>    #include <vector>        namespace hmi {        enum class EvType { KeyPress, UpdateRequest };        struct Ev {        EvType type;        int key = 0;    };        class SimWidget {    public:        virtual ~SimWidget() = default;            void install_event_filter(SimWidget *watcher) {            if (watcher && watcher != this) {                m_filters.erase(                    std::remove(m_filters.begin(), m_filters.end(), watcher),                    m_filters.end());                m_filters.push_back(watcher);            }        }            virtual bool event_filter(SimWidget *, Ev *) { return false; }            virtual bool event(Ev *e) {            if (e->type == EvType::KeyPress) {                ++key_hits;                last_key = e->key;                order_log.push_back(1);                return true;            }            if (e->type == EvType::UpdateRequest) {                ++paint_passes;                order_log.push_back(2);                return true;            }            return false;        }            const std::vector<SimWidget *> &filters() const noexcept { return m_filters; }            int key_hits = 0;        int paint_passes = 0;        int last_key = 0;        std::vector<int> order_log;        private:        std::vector<SimWidget *> m_filters;    };        class EventDispatcher {    public:        static bool send_event(SimWidget *dst, Ev *e) {          const auto &flts = dst->filters();            for (auto it = flts.rbegin(); it != flts.rend(); ++it) {                if ((*it)->event_filter(dst, e)) {                    return true;                }            }            return dst->event(e);        }            void post_event(SimWidget *dst, std::unique_ptr<Ev> e, int prio) {          if (e->type == EvType::UpdateRequest) {                for (const auto &q : m_queue) {                    if (q.dst == dst && q.ev->type == EvType::UpdateRequest) {                        return; // Coalesce duplicate pending UpdateRequest!                    }                }            }            m_queue.push_back({prio, m_seq++, dst, std::move(e)});        }            std::size_t drain() {            std::sort(m_queue.begin(), m_queue.end(),                      [] (const Queued &a, const Queued &b) {                          return (a.prio != b.prio) ? (a.prio > b.prio) : (a.seq < b.seq);                      });            std::size_t dispatched = 0;            while (!m_queue.empty()) {                Queued cur = std::move(m_queue.front());                m_queue.erase(m_queue.begin());                send_event(cur.dst, cur.ev.get());                ++dispatched;            }            return dispatched;        }        private:        struct Queued {            int prio;            std::size_t seq;            SimWidget *dst;            std::unique_ptr<Ev> ev;        };        std::size_t m_seq = 0;        std::vector<Queued> m_queue;    };        struct AuditFilter final : public SimWidget {        int seen = 0;        bool event_filter(SimWidget *, Ev *) override { ++seen; return false; }    };        struct DoorFilter final : public SimWidget {        bool closed = false;        int blocked = 0;        bool event_filter(SimWidget *, Ev *e) override {            if (!closed && e->type == EvType::KeyPress && e->key == 100) {                ++blocked;                return true;            }            return false;        }    };        } // namespace hmi        int main() {        hmi::EventDispatcher loop;        hmi::SimWidget jog_btn;        hmi::AuditFilter audit;        hmi::DoorFilter door;            jog_btn.install_event_filter(&audit);        jog_btn.install_event_filter(&door); // Installed 2nd -> runs 1st (LIFO)!            hmi::Ev stack_up{hmi::EvType::KeyPress, 100};        hmi::EventDispatcher::send_event(&jog_btn, &stack_up);        assert(door.blocked == 1 && audit.seen == 0 && jog_btn.key_hits == 0);            door.closed = true;        hmi::EventDispatcher::send_event(&jog_btn, &stack_up);        assert(door.blocked == 1 && audit.seen == 1 && jog_btn.key_hits == 1);            jog_btn.order_log.clear();        for (int i = 0; i < 6; ++i) {            loop.post_event(&jog_btn,                            std::make_unique<hmi::Ev>(hmi::Ev{hmi::EvType::UpdateRequest, 0}),                            -1);        }        loop.post_event(&jog_btn,                        std::make_unique<hmi::Ev>(hmi::Ev{hmi::EvType::KeyPress, 27}), +1);            const std::size_t drained = loop.drain();        assert(drained == 2 && jog_btn.paint_passes == 1 && jog_btn.last_key == 27);        assert((jog_btn.order_log == std::vector<int>{1, 2}));            std::printf("Events blocked=%d audit=%d keys=%d paints=%d drained=%zu\n",                    door.blocked, audit.seen, jog_btn.key_hits,                    jog_btn.paint_passes, drained);        return 0;    }
  1. Reverse iterator (flts.rbegin()..rend()) enforces Qt's LIFO eventFilter execution order.
  2. Duplicate UpdateRequest events targeting the same widget coalesce in the posted queue before drain().

Confirming LIFO Interception and Repaint Coalescing

Verify ./verify prints Events blocked=1 audit=1 keys=2 paints=1 drained=2. Installing door after audit caused door to intercept the unsafe keystroke before audit could even log it (audit=0 on the blocked pass, 1 after closing the guard), and order_log == {1, 2} proved that priority +1 (KeyPress) executed ahead of coalesced priority -1 (UpdateRequest).

Notice how encoding post_event's parameter as std::unique_ptr<Ev> in C++20 makes passing a stack address impossible at compile time!

learner@ksa: ~/gl-q01/m03-l02
learner@ksa:~/gl-q01/m03-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m03-l02./verifyEvents blocked=1 audit=3 keys=2 paints=1 drained=2learner@ksa:~/gl-q01/m03-l02
strace — learner@ksa: ~/gl-q01/m03-l02
learner@ksa:~/gl-q01/m03-l02strace -e trace=write,exit_group ./verifywrite(1, "Events blocked=1 audit=3 keys=2 "..., 51) = 51exit_group(0)                           = ?+++ exited with 0 +++

Blank Widgets From Bad Filters & Nested processEvents() Re-Entrancy

You now control every stage of QEvent delivery: stack sendEvent versus heap postEvent, LowEventPriority repaint compression via update(), and centralized LIFO eventFilter interlocks.

Next, Lesson 3.3 completes Module 3 by connecting the event loop to hardware time: CLOCK_MONOTONIC timer heaps, Qt::PreciseTimer versus Qt::CoarseTimer's 5% coalescing window, and why long synchronous slots starve QPaintEvent frames.

Returning true by Accident at the Bottom of eventFilter():

  • Symptom: After installing a custom eventFilter on a QLineEdit or QPushButton, the widget turns completely blank and ignores mouse clicks and focus.
  • Root Cause: Returning true on the default path tells QCoreApplication::notify that EVERY event—including QEvent::Paint, QEvent::Resize, and QEvent::MouseButtonPress—was consumed!
  • Fix: Return true ONLY inside the narrow if (...) branch that intentionally blocks an event, and always end with return QObject::eventFilter(watched, event); (false).

Sprinkling QCoreApplication::processEvents() Inside Long Slot Loops:

  • Symptom: An engineer adds QCoreApplication::processEvents() inside a file-export slot to 'keep the UI responsive', and clicking Close mid-export crashes inside the still-running export loop!
  • Root Cause: processEvents() spins a nested event loop right inside your active stack frame, allowing user clicks or DeferredDelete events to re-enter slots or destroy this before the outer loop finishes!
  • Fix: Never patch slow GUI-thread work with processEvents(); move blocking I/O or heavy math onto a worker thread (or chunk small non-blocking steps on a 0 ms / periodic QTimer).

Guided Practice

Modify install_event_filter in verify.cpp to verify what happens when the SAME filter &audit is installed a second time after &door: confirm that Qt removes the earlier &audit entry and appends &audit at the back, promoting &audit to run FIRST in LIFO order!

Independent Practice

Design an inactivity screen-dimmer IdleTouchFilter installed once on QApplication::instance() (global application event filter!) that observes QEvent::MouseButtonPress, QEvent::TouchBegin, and QEvent::KeyPress across every widget in the application to reset a backlight timer while always returning false.

Verification Checks

quiz · 1 of 3

What happens if an engineer writes QEvent ev(QEvent::User); QCoreApplication::postEvent(panel, &ev);?

quiz · 2 of 3

Filter Logger is installed first via btn->installEventFilter(logger), followed by btn->installEventFilter(interlock). When interlock->eventFilter returns true, what executes?

quiz · 3 of 3

Why should a 500 Hz telemetry slot call gauge->update() rather than gauge->repaint()?

Key takeaways

  • QCoreApplication::sendEvent(dst, &ev) dispatches a stack-allocated QEvent synchronously on the current call stack without deleting ev, whereas postEvent(dst, new Ev) queues a heap event asynchronously and deletes it after delivery.
  • Passing the address of a stack-allocated QEvent into QCoreApplication::postEvent causes fatal heap corruption when the event dispatcher drains the queue and executes delete event.
  • Pre-target watchers installed via target->installEventFilter(filterObj) execute in LIFO order (last installed runs first); returning true consumes the event immediately while returning false forwards it toward target->event().
  • Qt compresses queued QEvent::UpdateRequest events posted by QWidget::update() so bursts of state changes within one event-loop turn coalesce into a single QPaintEvent raster pass.
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure