深入了解事件处理系统对于每个学习Qt人来说非常重要,可以说,Qt是以事件驱动的UI工具集。 大家熟知Signals/Slots在多线程的实现也依赖于Qt的事件处理机制。
在Qt中,事件被封装成一个个对象,所有的事件均继承自抽象类QEvent. 接下来依次谈谈Qt中有谁来产生、分发、接受和处理事件:
1. 谁来产生事件: 最容易想到的是我们的输入设备,比如键盘、鼠标产生的
keyPressEvent,keyReleaseEvent,mousePressEvent,mouseReleaseEvent事件(他们被封装成QMouseEvent和QKeyEvent),这些事件来自于底层的操作系统,它们以异步的形式通知Qt事件处理系统,后文会仔细道来。当然Qt自己也会产生很多事件,比如QObject::startTimer()会触发QTimerEvent. 用户的程序可还以自己定制事件。
2. 谁来接受和处理事件:答案是QObject。在Qt的内省机制剖析一文已经介绍QObject 类是整个Qt对象模型的心脏,事件处理机制是QObject三大职责(内存管理、内省(intropection)与事件处理制)之一。任何一个想要接受并处理事件的对象均须继承自QObject,可以选择重载QObject::event()函数或事件的处理权转给父类。
3. 谁来负责分发事件:对于non-GUI的Qt程序,是由QCoreApplication负责将QEvent分发给QObject的子类-Receiver. 对于Qt GUI程序,由QApplication来负责。
接下来,将通过对代码的解析来看看QT是利用event loop从事件队列中获取用户输入事件,又是如何将事件转义成QEvents,并分发给相应的QObject处理。
- #include <QApplication>
- #include "widget.h"
-
- int main(int argc, char *argv[])
- {
- QApplication app(argc, argv);
- Widget window;
- window.show();
- return app.exec();
- }
-
- int QApplication::exec()
- {
-
-
- return QCoreApplication::exec();
- }
-
- int QCoreApplication::exec()
- {
-
- QThreadData *threadData = self->d_func()->threadData;
- if (threadData != QThreadData::current()) {
- qWarning("%s::exec: Must be called from the main thread", self->metaObject()->className());
- return -1;
- }
-
- if (!threadData->eventLoops.isEmpty()) {
- qWarning("QCoreApplication::exec: The event loop is already running");
- return -1;
- }
- ...
- QEventLoop eventLoop;
- self->d_func()->in_exec = true;
- self->d_func()->aboutToQuitEmitted = false;
-
- int returnCode = eventLoop.exec();
- ....
- }
- return returnCode;
- }
-
- int QEventLoop::exec(ProcessEventsFlags flags)
- {
-
- Q_D(QEventLoop);
- try {
-
- while (!d->exit)
- processEvents(flags | WaitForMoreEvents | EventLoopExec);
- } catch (...) {}
- }
-
- bool QEventLoop::processEvents(ProcessEventsFlags flags)
- {
- Q_D(QEventLoop);
- if (!d->threadData->eventDispatcher)
- return false;
- if (flags & DeferredDeletion)
- QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
-
- return d->threadData->eventDispatcher->processEvents(flags);
- }
-
-
-
-
- bool QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags)
- {
- Q_D(QEventDispatcherWin32);
- if (!d->internalHwnd)
- createInternalHwnd();
- d->interrupt = false;
- emit awake();
- bool canWait;
- bool retVal = false;
- bool seenWM_QT_SENDPOSTEDEVENTS = false;
- bool needWM_QT_SENDPOSTEDEVENTS = false;
- do {
- DWORD waitRet = 0;
- HANDLE pHandles[MAXIMUM_WAIT_OBJECTS - 1];
- QVarLengthArray<MSG> processedTimers;
- while (!d->interrupt) {
- DWORD nCount = d->winEventNotifierList.count();
- Q_ASSERT(nCount < MAXIMUM_WAIT_OBJECTS - 1);
- MSG msg;
- bool haveMessage;
- if (!(flags & QEventLoop::ExcludeUserInputEvents) && !d->queuedUserInputEvents.isEmpty()) {
-
- haveMessage = true;
-
- msg = d->queuedUserInputEvents.takeFirst();
- } else if(!(flags & QEventLoop::ExcludeSocketNotifiers) && !d->queuedSocketEvents.isEmpty()) {
-
- haveMessage = true;
- msg = d->queuedSocketEvents.takeFirst();
- } else {
- haveMessage = PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
- if (haveMessage && (flags & QEventLoop::ExcludeUserInputEvents)
- && ((msg.message >= WM_KEYFIRST
- && msg.message <= WM_KEYLAST)
- || (msg.message >= WM_MOUSEFIRST
- && msg.message <= WM_MOUSELAST)
- || msg.message == WM_MOUSEWHEEL
- || msg.message == WM_MOUSEHWHEEL
- || msg.message == WM_TOUCH
- #ifndef QT_NO_GESTURES
- || msg.message == WM_GESTURE
- || msg.message == WM_GESTURENOTIFY
- #endif
- || msg.message == WM_CLOSE)) {
-
- haveMessage = false;
- d->queuedUserInputEvents.append(msg);
- }
- if (haveMessage && (flags & QEventLoop::ExcludeSocketNotifiers)
- && (msg.message == WM_QT_SOCKETNOTIFIER && msg.hwnd == d->internalHwnd)) {
-
- haveMessage = false;
- d->queuedSocketEvents.append(msg);
- }
- }
- ....
- if (!filterEvent(&msg)) {
- TranslateMessage(&msg);
-
-
- DispatchMessage(&msg);
- }
- }
- }
- } while (canWait);
- ...
- return retVal;
- }
-
- extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
- {
- ...
-
- result = widget->translateMouseEvent(msg);
- ...
- }
-
从Section 1~Section7, Qt进入QApplication的event loop,经过层层委任,最终QEventloop的processEvent将通过与平台相关的QAbstractEventDispatcher的子类QEventDispatcherWin32获得用户的用户输入事件,并将其打包成message后,通过标准Windows API ,把消息传递给了Windows OS,Windows OS得到通知后回调QtWndProc, 至此事件的分发与处理完成了一半的路程。
在下文中,我们将进一步讨论当我们收到来在Windows的回调后,事件又是怎么一步步打包成QEvent并通过QApplication分发给最终事件的接受和处理者QObject::event.
我们在上文中,介绍了Qt框架的事件处理机制:事件的产生、分发、接受和处理,并以视窗系统鼠标点击QWidget为例,对代码进行了剖析,向大家分析了Qt框架如何通过Event Loop处理进入处理消息队列循环,如何一步一步委派给平台相关的函数获取、打包用户输入事件交给视窗系统处理,函数调用栈如下:
- main(int, char **)
- QApplication::exec()
- QCoreApplication::exec()
- QEventLoop::exec(ProcessEventsFlags )
- QEventLoop::processEvents(ProcessEventsFlags )
- QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags)
本文将介绍Qt app在视窗系统回调后,事件又是怎么一步步通过QApplication分发给最终事件的接受和处理者QWidget::event, (QWidget继承Object,重载其虚函数event),以下所有的讨论都将嵌入在源码之中。
- QT_WIN_CALLBACK QtWndProc(HWNDhwnd, UINT message, WPARAM wParam, LPARAM lParam) bool QETWidget::translateMouseEvent(const MSG &msg)
- bool QApplicationPrivate::sendMouseEvent(...)
- inline bool QCoreApplication::sendSpontaneousEvent(QObject *receiver, QEvent *event)
- bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event)
- bool QApplication::notify(QObject *receiver, QEvent *e)
- bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
- bool QWidget::event(QEvent *event)
-
- QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
- {
- ...
-
- if (qt_is_translatable_mouse_event(message)) {
- if (QApplication::activePopupWidget() != 0) {
- POINT curPos = msg.pt;
-
- QWidget* w = QApplication::widgetAt(curPos.x, curPos.y);
- if (w)
- widget = (QETWidget*)w;
- }
- if (!qt_tabletChokeMouse) {
-
-
- result = widget->translateMouseEvent(msg);
- ...
- }
-
-
- bool QETWidget::translateMouseEvent(const MSG &msg)
- {
-
-
-
-
- res = QApplicationPrivate::sendMouseEvent(widget, &e, alienWidget, this, &qt_button_down, qt_last_mouse_receiver);
- }
-
- bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
- QWidget *alienWidget, QWidget *nativeWidget,
- QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,
- bool spontaneous)
- {
-
-
- spontaneous事件
- if (spontaneous)
- result = QApplication::sendSpontaneousEvent(receiver, event); ==〉Section 2-4
- else
- result = QApplication::sendEvent(receiver, event);
- }
-
- inline bool QCoreApplication::sendSpontaneousEvent(QObject *receiver, QEvent *event)
- {
-
-
- if (event) event->spont = true; return self ? self->notifyInternal(receiver, event) : false;
- }
-
- bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event)
- {
-
-
- ...
-
- QObjectPrivate *d = receiver->d_func();
- QThreadData *threadData = d->threadData;
- ++threadData->loopLevel;
- bool returnValue;
- QT_TRY {
-
- returnValue = notify(receiver, event);
- } QT_CATCH (...) {
- --threadData->loopLevel;
- QT_RETHROW;
- }
- }
-
-
- bool QApplication::notify(QObject *receiver, QEvent *e)
- {
-
- ..
- switch ( e->type())
- {
- ...
- case QEvent::MouseButtonPress:
- case QEvent::MouseButtonRelease:
- case QEvent::MouseButtonDblClick:
- case QEvent::MouseMove:
- ...
-
- res = d->notify_helper(w, w == receiver ? mouse : &me);
- e->spont = false;
- break;
- }
- ...
- }
-
- bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
- {
- ...
-
-
- if (sendThroughObjectEventFilters(receiver, e))
- return true;
-
- bool consumed = receiver->event(e);
- e->spont = false;
- }
-
-
- bool QWidget::event(QEvent *event)
- {
- ...
- switch(event->type()) {
- case QEvent::MouseButtonPress:
-
-
-
-
- #if 0
- resetInputContext();
- #endif
-
- mousePressEvent((QMouseEvent*)event);
- break;
- }