Qt-UI

Events

Event Loop | | Specializing QWidget

Some events, such as mouse and key event, come from the window system; some, such as timer event, come from other sources; some come from the application itself.

Basic Event Types

  • paint event (QPaintEvent → QObject::paintEvent())
  • resize event (QResizeEvent → QObject::resizeEvent())
  • mouse event (QMouseEvent → QObject::mouseEvent())
  • key event (QKeyEvent → QObject::keyEvent())
  • wheel events (QWheelEvent → QObject::wheelEvent())
  • timer event (QTimerEvent → QObject::timerEvent())

Each event subclasses QEvent and adds event-specific functions. For example, QResizeEvent adds size() and oldSize() to enable widgets to discover how their dimensions have been changed.

Timer Events

Timer events can be created on any QObject simply by calling its startTimer(ms) method with the number of milliseconds after which the timer event is scheduled to be repeated.

The startTimer() method returns a timer id which can be passed to stopTimer() to stop the timer from firing repeatedly.

Event Filters

Sometimes an object needs to look at, and possibly intercept, the events that are delivered to another object. For example, dialogs commonly want to filter key presses for some widgets.

The QObject::installEventFilter() function enables this by setting up an event filter, causing a nominated QObject filter object to receive the events for a target object in its eventFilter() function. This filter functions gets to see the events before the target object processes them. If the inspected event should not be processd further, because it is handled by the target, the event filter function returns true.

Sending Events

Many applications require to send their own events. Custom events are created by subclassing from QEvent. Sending those events can be done in exactly the same way as the Qt main event loop sends events.

Events can be sent either immediately via QCoreApplication::sendEvent() or stored in a queue for later execution via QCoreApplication::postEvent().

Sending customized events may require a modification of the event handler to check and dispatch the cutom event type.

Events and Threads

Qt methods that modify UI elements need to be called from the same thread as the Qt main event loop. It can’t be done from another thread.

Calling methods on objects in another thread can be achieved by sending custom events to the thread of the target object. Sending events is thread-safe. Events can be sent to all threads that have an event loop running.

QObject is not thread-safe though. If you call a QObject method from multiple threads you have to put a mutex around the code that accesses shared data.

Another solution is to use Queued Connections to call methods in other threads.


Event Loop | | Specializing QWidget

Options: