[ fromfile: eventloop.xml id: eventloop ]
Interactive Qt applications with GUI have a different control flow from console applications and filter applications [28] because they are event-based, and often multi-threaded. In such applications, Objects are frequently sending messages to each other, making a linear hand-trace through the code rather difficult.
The Qt class QEvent encapsulates the notion of an event.
QEvent 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 actions of the user (e.g., 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 that can identify the particular kind of event.
A typical Qt program creates objects, connects them, and then tells the application to exec().
At that point, the objects can send information to each other in a variety of ways.
QWidgets send QEvents to other QObjects in response to user actions such as mouse clicks and keyboard events.
A widget can also respond to events from the window manager such as repaints, resizes, or close events.
Furthermore, QObjects can transmit information to one another by means of signals and slots.
Each QWidget can be specialized to handle keyboard and mouse events in its own way.
Some widgets will emit a signal in response to receiving an event.
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 only get called in response to certain events. The event loop generally continues running until a terminating event occurs (e.g., the user clicks on ).
Example 9.5 shows the main() function for a simple application that initiates the event loop by calling exec().
Example 9.5. src/eventloop/eventloop.cpp
[ . . . . ]
int main(int argc, char * argv[]) {
QApplication myapp(argc, argv);
QWidget rootWidget;
setGui(&rootWidget);
rootWidget.show();
return myapp.exec();
};
| Every GUI, multithreaded, or event-driven Qt Application must have a QApplication object defined at the top of main(). | |
| Show the widget on the screen. | |
| Enter an event loop. |
When we run this program, we will first see a widget on the screen, like Figure 9.4.
We can type in the QTextEdit on the screen, or click on the button. When is clicked, a widget like Figure 9.5 is superimposed on our original widget.
This message dialog knows how to self-destruct, because it has its own buttons and actions.
[28] A filter application is not interactive - It simply reads from standard input and writes to standard output.
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |