8.3.  QApplication and the Event Loop

[ fromfile: eventloop.xml id: eventloop ]

Interactive Qt applications with GUI have a different control flow from console applications and filter applications.[68] This is because they are event-based. In such applications, objects are frequently sending messages to one another through an intermediate object. This can make a linear hand-trace through the code rather difficult.

The Qt class QEvent encapsulates the notion of a low-level event. It is the base class for several specific event classes such as QActionEvent, QFileOpenEvent, QHoverEvent, QInputEvent, QMouseEvent, and so forth. QEvent objects can be created by the window system in response to an action of the user (e.g., a QMouseEvent), at specified time intervals (QTimerEvent), or explicitly by an application program. The type() member function returns an enum that has nearly a hundred specific values to identify the particular kind of event (e.g., Close, DragEnter, DragMove, Drop, Enter, GrabMouse, HoverEnter, KeyPress, MouseButtonDblClick, MouseMove, Resize, and so on).

An event loop is a program structure that permits events to be prioritized, enqueued, and dispatched to objects. Writing an event based application means implementing a passive interface of functions that get called in response to things such as mouse clicks, touch pad gestures, key clicks, signals being emitted, window manager events, or messages from other programs. The event loop generally continues running until a terminating event occurs (for example, the user invokes a Quit action, the last window is closed, and so on).

A typical Qt program creates objects, connects them, and then tells the application to exec(). At that point, the application enters the event loop. The objects can then send information to each other in a variety of ways. A typical main() function looks like this.

  int main(int argc, char ** argv) {
    QApplication app(argc, argv);
    FancyWidget fwidg;
    fwidg.show();        // returns immediately
    return app.exec();   // enters event loop
  }
  

The call to the QApplication::exec() function occurs in the return statement at the end of main(). The entire active part of the application begins with that function call and ends when it returns. The details are in the definition and implementation of the FancyWidget class. That is quite typical of Qt event loop applications.



[68] A filter application is not interactive. It simply reads from standard input and writes to standard output.