Qt事件处理机制

来源:互联网 发布:手机设置网络共享 编辑:程序博客网 时间:2024/06/02 07:29
 

本篇来介绍Qt 事件处理机制 。深入了解事件处理系统对于每个学习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处理。

  1. #include <QApplication>
  2. #include "widget.h"
  3. //Section 1
  4. int main(int argc, char *argv[])
  5. {
  6. QApplication app(argc, argv);
  7. Widget window; // Widget 继承自QWidget
  8. window.show();
  9. return app.exec(); // 进入Qpplication事件循环,见section 2
  10. }
  11. // Section 2:
  12. int QApplication::exec()
  13. {
  14. //skip codes
  15. //简单的交给QCoreApplication来处理事件循环=〉section 3
  16. return QCoreApplication::exec();
  17. }
  18. // Section 3
  19. int QCoreApplication::exec()
  20. {
  21. //得到当前Thread数据
  22. QThreadData *threadData = self->d_func()->threadData;
  23. if (threadData != QThreadData::current()) {
  24. qWarning("%s::exec: Must be called from the main thread", self->metaObject()->className());
  25. return -1;
  26. }
  27. //检查event loop是否已经创建
  28. if (!threadData->eventLoops.isEmpty()) {
  29. qWarning("QCoreApplication::exec: The event loop is already running");
  30. return -1;
  31. }
  32. ...
  33. QEventLoop eventLoop;
  34. self->d_func()->in_exec = true;
  35. self->d_func()->aboutToQuitEmitted = false;
  36. //委任QEventLoop 处理事件队列循环 ==> Section 4
  37. int returnCode = eventLoop.exec();
  38. ....
  39. }
  40. return returnCode;
  41. }
  42. // Section 4
  43. int QEventLoop::exec(ProcessEventsFlags flags)
  44. {
  45. //这里的实现代码不少,最为重要的是以下几行
  46. Q_D(QEventLoop); // 访问QEventloop私有类实例d
  47. try {
  48. //只要没有遇见exit,循环派发事件
  49. while (!d->exit)
  50. processEvents(flags | WaitForMoreEvents | EventLoopExec);
  51. } catch (...) {}
  52. }
  53. // Section 5
  54. bool QEventLoop::processEvents(ProcessEventsFlags flags)
  55. {
  56. Q_D(QEventLoop);
  57. if (!d->threadData->eventDispatcher)
  58. return false;
  59. if (flags & DeferredDeletion)
  60. QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
  61. //将事件派发给与平台相关的QAbstractEventDispatcher子类 =>Section 6
  62. return d->threadData->eventDispatcher->processEvents(flags);
  63. }
  64. #include <QApplication>
  65. #include "widget.h"
  66. //Section 1
  67. int main(int argc, char *argv[])
  68. {
  69. QApplication app(argc, argv);
  70. Widget window; // Widget 继承自QWidget
  71. window.show();
  72. return app.exec(); // 进入Qpplication事件循环,见section 2
  73. }
  74. // Section 2:
  75. int QApplication::exec()
  76. {
  77. //skip codes
  78. //简单的交给QCoreApplication来处理事件循环=〉section 3
  79. return QCoreApplication::exec();
  80. }
  81. // Section 3
  82. int QCoreApplication::exec()
  83. {
  84. //得到当前Thread数据
  85. QThreadData *threadData = self->d_func()->threadData;
  86. if (threadData != QThreadData::current()) {
  87. qWarning("%s::exec: Must be called from the main thread", self->metaObject()->className());
  88. return -1;
  89. }
  90. //检查event loop是否已经创建
  91. if (!threadData->eventLoops.isEmpty()) {
  92. qWarning("QCoreApplication::exec: The event loop is already running");
  93. return -1;
  94. }
  95. ...
  96. QEventLoop eventLoop;
  97. self->d_func()->in_exec = true;
  98. self->d_func()->aboutToQuitEmitted = false;
  99. //委任QEventLoop 处理事件队列循环 ==> Section 4
  100. int returnCode = eventLoop.exec();
  101. ....
  102. }
  103. return returnCode;
  104. }
  105. // Section 4
  106. int QEventLoop::exec(ProcessEventsFlags flags)
  107. {
  108. //这里的实现代码不少,最为重要的是以下几行
  109. Q_D(QEventLoop); // 访问QEventloop私有类实例d
  110. try {
  111. //只要没有遇见exit,循环派发事件
  112. while (!d->exit)
  113. processEvents(flags | WaitForMoreEvents | EventLoopExec);
  114. } catch (...) {}
  115. }
  116. // Section 5
  117. bool QEventLoop::processEvents(ProcessEventsFlags flags)
  118. {
  119. Q_D(QEventLoop);
  120. if (!d->threadData->eventDispatcher)
  121. return false;
  122. if (flags & DeferredDeletion)
  123. QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
  124. //将事件派发给与平台相关的QAbstractEventDispatcher子类 =>Section 6
  125. return d->threadData->eventDispatcher->processEvents(flags);
  126. }
  127. // Section 6,QTDIR\src\corelib\kernel\qeventdispatcher_win.cpp
  128. // 这段代码是完成与windows平台相关的windows c++。 以跨平台著称的Qt同时也提供了对Symiban,Unix等平台的消息派发支持
  129. // 其事现分别封装在QEventDispatcherSymbian和QEventDispatcherUNIX
  130. // QEventDispatcherWin32派生自QAbstractEventDispatcher.
  131. bool QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags)
  132. {
  133. Q_D(QEventDispatcherWin32);
  134. if (!d->internalHwnd)
  135. createInternalHwnd();
  136. d->interrupt = false;
  137. emit awake();
  138. bool canWait;
  139. bool retVal = false;
  140. bool seenWM_QT_SENDPOSTEDEVENTS = false;
  141. bool needWM_QT_SENDPOSTEDEVENTS = false;
  142. do {
  143. DWORD waitRet = 0;
  144. HANDLE pHandles[MAXIMUM_WAIT_OBJECTS - 1];
  145. QVarLengthArray<MSG> processedTimers;
  146. while (!d->interrupt) {
  147. DWORD nCount = d->winEventNotifierList.count();
  148. Q_ASSERT(nCount < MAXIMUM_WAIT_OBJECTS - 1);
  149. MSG msg;
  150. bool haveMessage;
  151. if (!(flags & QEventLoop::ExcludeUserInputEvents) && !d->queuedUserInputEvents.isEmpty()) {
  152. // process queued user input events
  153. haveMessage = true;
  154. //从处理用户输入队列中取出一条事件
  155. msg = d->queuedUserInputEvents.takeFirst();
  156. } else if(!(flags & QEventLoop::ExcludeSocketNotifiers) && !d->queuedSocketEvents.isEmpty()) {
  157. // 从处理socket队列中取出一条事件
  158. haveMessage = true;
  159. msg = d->queuedSocketEvents.takeFirst();
  160. } else {
  161. haveMessage = PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
  162. if (haveMessage && (flags & QEventLoop::ExcludeUserInputEvents)
  163. && ((msg.message >= WM_KEYFIRST
  164. && msg.message <= WM_KEYLAST)
  165. || (msg.message >= WM_MOUSEFIRST
  166. && msg.message <= WM_MOUSELAST)
  167. || msg.message == WM_MOUSEWHEEL
  168. || msg.message == WM_MOUSEHWHEEL
  169. || msg.message == WM_TOUCH
  170. #ifndef QT_NO_GESTURES
  171. || msg.message == WM_GESTURE
  172. || msg.message == WM_GESTURENOTIFY
  173. #endif
  174. || msg.message == WM_CLOSE)) {
  175. // 用户输入事件入队列,待以后处理
  176. haveMessage = false;
  177. d->queuedUserInputEvents.append(msg);
  178. }
  179. if (haveMessage && (flags & QEventLoop::ExcludeSocketNotifiers)
  180. && (msg.message == WM_QT_SOCKETNOTIFIER && msg.hwnd == d->internalHwnd)) {
  181. // socket 事件入队列,待以后处理
  182. haveMessage = false;
  183. d->queuedSocketEvents.append(msg);
  184. }
  185. }
  186. ....
  187. if (!filterEvent(&msg)) {
  188. TranslateMessage(&msg);
  189. //将事件打包成message调用Windows API派发出去
  190. //分发一个消息给窗口程序。消息被分发到回调函数,将消息传递给windows系统,windows处理完毕,会调用回调函数 => section 7
  191. DispatchMessage(&msg);
  192. }
  193. }
  194. }
  195. } while (canWait);
  196. ...
  197. return retVal;
  198. }
  199. // Section 6,QTDIR\src\corelib\kernel\qeventdispatcher_win.cpp
  200. // 这段代码是完成与windows平台相关的windows c++。 以跨平台著称的Qt同时也提供了对Symiban,Unix等平台的消息派发支持
  201. // 其事现分别封装在QEventDispatcherSymbian和QEventDispatcherUNIX
  202. // QEventDispatcherWin32派生自QAbstractEventDispatcher.
  203. bool QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags)
  204. {
  205. Q_D(QEventDispatcherWin32);
  206. if (!d->internalHwnd)
  207. createInternalHwnd();
  208. d->interrupt = false;
  209. emit awake();
  210. bool canWait;
  211. bool retVal = false;
  212. bool seenWM_QT_SENDPOSTEDEVENTS = false;
  213. bool needWM_QT_SENDPOSTEDEVENTS = false;
  214. do {
  215. DWORD waitRet = 0;
  216. HANDLE pHandles[MAXIMUM_WAIT_OBJECTS - 1];
  217. QVarLengthArray<MSG> processedTimers;
  218. while (!d->interrupt) {
  219. DWORD nCount = d->winEventNotifierList.count();
  220. Q_ASSERT(nCount < MAXIMUM_WAIT_OBJECTS - 1);
  221. MSG msg;
  222. bool haveMessage;
  223. if (!(flags & QEventLoop::ExcludeUserInputEvents) && !d->queuedUserInputEvents.isEmpty()) {
  224. // process queued user input events
  225. haveMessage = true;
  226. //从处理用户输入队列中取出一条事件
  227. msg = d->queuedUserInputEvents.takeFirst();
  228. } else if(!(flags & QEventLoop::ExcludeSocketNotifiers) && !d->queuedSocketEvents.isEmpty()) {
  229. // 从处理socket队列中取出一条事件
  230. haveMessage = true;
  231. msg = d->queuedSocketEvents.takeFirst();
  232. } else {
  233. haveMessage = PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
  234. if (haveMessage && (flags & QEventLoop::ExcludeUserInputEvents)
  235. && ((msg.message >= WM_KEYFIRST
  236. && msg.message <= WM_KEYLAST)
  237. || (msg.message >= WM_MOUSEFIRST
  238. && msg.message <= WM_MOUSELAST)
  239. || msg.message == WM_MOUSEWHEEL
  240. || msg.message == WM_MOUSEHWHEEL
  241. || msg.message == WM_TOUCH
  242. #ifndef QT_NO_GESTURES
  243. || msg.message == WM_GESTURE
  244. || msg.message == WM_GESTURENOTIFY
  245. #endif
  246. || msg.message == WM_CLOSE)) {
  247. // 用户输入事件入队列,待以后处理
  248. haveMessage = false;
  249. d->queuedUserInputEvents.append(msg);
  250. }
  251. if (haveMessage && (flags & QEventLoop::ExcludeSocketNotifiers)
  252. && (msg.message == WM_QT_SOCKETNOTIFIER && msg.hwnd == d->internalHwnd)) {
  253. // socket 事件入队列,待以后处理
  254. haveMessage = false;
  255. d->queuedSocketEvents.append(msg);
  256. }
  257. }
  258. ....
  259. if (!filterEvent(&msg)) {
  260. TranslateMessage(&msg);
  261. //将事件打包成message调用Windows API派发出去
  262. //分发一个消息给窗口程序。消息被分发到回调函数,将消息传递给windows系统,windows处理完毕,会调用回调函数 => section 7
  263. DispatchMessage(&msg);
  264. }
  265. }
  266. }
  267. } while (canWait);
  268. ...
  269. return retVal;
  270. }
  271. // Section 7 windows窗口回调函数 定义在QTDIR\src\gui\kernel\qapplication_win.cpp
  272. extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  273. {
  274. ...
  275. //将消息重新封装成QEvent的子类QMouseEvent ==> Section 8
  276. result = widget->translateMouseEvent(msg);
  277. ...
  278. }
  279. // Section 7 windows窗口回调函数 定义在QTDIR\src\gui\kernel\qapplication_win.cpp
  280. extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  281. {
  282. ...
  283. //将消息重新封装成QEvent的子类QMouseEvent ==> Section 8
  284. result = widget->translateMouseEvent(msg);
  285. ...
  286. }

从Section 1~Section7, Qt进入QApplication的event loop,经过层层委任,最终QEventloop的processEvent将通过与平台相关的QAbstractEventDispatcher的子类QEventDispatcherWin32获得用户的用户输入事件,并将其打包成message后,通过标准Windows API ,把消息传递给了Windows OS,Windows OS得到通知后回调QtWndProc, 至此事件的分发与处理完成了一半的路程。

小结:Qt 事件处理机制 (上篇)的内容介绍完了,在下文中,我们将进一步讨论当我们收到来在Windows的回调后,事件又是怎么一步步打包成QEvent并通过QApplication分发给最终事件的接受和处理者QObject::event.请继续看Qt 事件处理机制 (下篇)。最后希望本文能帮你解决问题!

继续我们上一篇文章继续介绍,Qt 事件处理机制 (上篇) 介绍了Qt框架的事件处理机制:事件的产生、分发、接受和处理,并以视窗系统鼠标点击QWidget为例,对代码进行了剖析,向大家分析了Qt框架如何通过Event Loop处理进入处理消息队列循环,如何一步一步委派给平台相关的函数获取、打包用户输入事件交给视窗系统处理,函数调用栈如下:

  1. main(int, char **)
  2. QApplication::exec()
  3. QCoreApplication::exec()
  4. QEventLoop::exec(ProcessEventsFlags )
  5. QEventLoop::processEvents(ProcessEventsFlags )
  6. QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags)

本文将介绍Qt app在视窗系统回调后,事件又是怎么一步步通过QApplication分发给最终事件的接受和处理者QWidget::event, (QWidget继承Object,重载其虚函数event),以下所有的讨论都将嵌入在源码之中。

  1. QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) bool QETWidget::translateMouseEvent(const MSG &msg)
  2. bool QApplicationPrivate::sendMouseEvent(...)
  3. inline bool QCoreApplication::sendSpontaneousEvent(QObject *receiver, QEvent *event)
  4. bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event)
  5. bool QApplication::notify(QObject *receiver, QEvent *e)
  6. bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
  7. bool QWidget::event(QEvent *event)
  8. // (续上文Section 7) Section 2-1:
  9. QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  10. {
  11. ...
  12. //检查message是否属于Qt可转义的鼠标事件
  13. if (qt_is_translatable_mouse_event(message)) {
  14. if (QApplication::activePopupWidget() != 0) {
  15. POINT curPos = msg.pt;
  16. //取得鼠标点击坐标所在的QWidget指针,它指向我们在main创建的widget实例
  17. QWidget* w = QApplication::widgetAt(curPos.x, curPos.y);
  18. if (w)
  19. widget = (QETWidget*)w;
  20. }
  21. if (!qt_tabletChokeMouse) {
  22. //对,就在这里。Windows的回调函数将鼠标事件分发回给了Qt Widget
  23. // => Section 2-2
  24. result = widget->translateMouseEvent(msg);
  25. ...
  26. }
  27. // Section 2-2 $QTDIR\src\gui\kernel\qapplication_win.cpp
  28. //该函数所在与Windows平台相关,主要职责就是把已windows格式打包的鼠标事件解包、翻译成QApplication可识别的QMouseEvent,QWidget.
  29. bool QETWidget::translateMouseEvent(const MSG &msg)
  30. {
  31. //.. 这里很长的代码给以忽略
  32. // 让我们看一下sendMouseEvent的声明
  33. // widget是事件的接受者; e是封装好的QMouseEvent
  34. // ==> Section 2-3
  35. res = QApplicationPrivate::sendMouseEvent(widget, &e, alienWidget, this, &qt_button_down, qt_last_mouse_receiver);
  36. }
  37. // Section 2-3 $QTDIR\src\gui\kernel\qapplication.cpp
  38. bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
  39. QWidget *alienWidget, QWidget *nativeWidget,
  40. QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,
  41. bool spontaneous)
  42. {
  43. //至此与平台相关代码处理完毕
  44. //MouseEvent默认的发送方式是spontaneous, 所以将执行sendSpontaneousEvent。 sendSpontaneousEvent() 与 sendEvent的代码实现几乎相同,
  45. 除了将QEvent的属性spontaneous标记不同。 这里是解释什么spontaneous事件:如果事件由应用程序之外产生的,比如一个系统事件。
  46. 显然MousePress事件是由视窗系统产生的一个的事件(详见上文Section 1~ Section 7),因此它是 spontaneous事件
  47. if (spontaneous)
  48. result = QApplication::sendSpontaneousEvent(receiver, event); ==〉Section 2-4
  49. else
  50. result = QApplication::sendEvent(receiver, event);
  51. }
  52. // (续上文Section 7) Section 2-1:
  53. QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  54. {
  55. ...
  56. //检查message是否属于Qt可转义的鼠标事件
  57. if (qt_is_translatable_mouse_event(message)) {
  58. if (QApplication::activePopupWidget() != 0) {
  59. POINT curPos = msg.pt;
  60. //取得鼠标点击坐标所在的QWidget指针,它指向我们在main创建的widget实例
  61. QWidget* w = QApplication::widgetAt(curPos.x, curPos.y);
  62. if (w)
  63. widget = (QETWidget*)w;
  64. }
  65. if (!qt_tabletChokeMouse) {
  66. //对,就在这里。Windows的回调函数将鼠标事件分发回给了Qt Widget
  67. // => Section 2-2
  68. result = widget->translateMouseEvent(msg);
  69. ...
  70. }
  71. // Section 2-2 $QTDIR\src\gui\kernel\qapplication_win.cpp
  72. //该函数所在与Windows平台相关,主要职责就是把已windows格式打包的鼠标事件解包、翻译成QApplication可识别的QMouseEvent,QWidget.
  73. bool QETWidget::translateMouseEvent(const MSG &msg)
  74. {
  75. //.. 这里很长的代码给以忽略
  76. // 让我们看一下sendMouseEvent的声明
  77. // widget是事件的接受者; e是封装好的QMouseEvent
  78. // ==> Section 2-3
  79. res = QApplicationPrivate::sendMouseEvent(widget, &e, alienWidget, this, &qt_button_down, qt_last_mouse_receiver);
  80. }
  81. // Section 2-3 $QTDIR\src\gui\kernel\qapplication.cpp
  82. bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
  83. QWidget *alienWidget, QWidget *nativeWidget,
  84. QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,
  85. bool spontaneous)
  86. {
  87. //至此与平台相关代码处理完毕
  88. //MouseEvent默认的发送方式是spontaneous, 所以将执行sendSpontaneousEvent。 sendSpontaneousEvent() 与 sendEvent的代码实现几乎相同,
  89. 除了将QEvent的属性spontaneous标记不同。 这里是解释什么spontaneous事件:如果事件由应用程序之外产生的,比如一个系统事件。
  90. 显然MousePress事件是由视窗系统产生的一个的事件(详见上文Section 1~ Section 7),因此它是spontaneous事件
  91. if (spontaneous)
  92. result = QApplication::sendSpontaneousEvent(receiver, event); ==〉Section 2-4
  93. else
  94. result = QApplication::sendEvent(receiver, event);
  95. }

  1. // Section 2-4 C:\Qt\4.7.1-Vs\src\corelib\kernel\qcoreapplication.h
  2. inline bool QCoreApplication::sendSpontaneousEvent(QObject *receiver, QEvent *event)
  3. {
  4. //将event标记为自发事件
  5. //进一步调用 2-5 QCoreApplication::notifyInternal
  6. if (event) event->spont = true; return self ? self->notifyInternal(receiver, event) : false;
  7. }
  8. // Section 2-5: $QTDIR\gui\kernel\qapplication.cpp
  9. bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event)
  10. {
  11. // 几行代码对于Qt Jambi (QT Java绑定版本) 和QSA (QT Script for Application)的支持
  12. ...
  13. // 以下代码主要意图为Qt强制事件只能够发送给当前线程里的对象,也就是说receiver->d_func()->threadData应该等于QThreadData::current()。
  14. 注意,跨线程的事件需要借助Event Loop来派发
  15. QObjectPrivate *d = receiver->d_func();
  16. QThreadData *threadData = d->threadData;
  17. ++threadData->loopLevel;
  18. bool returnValue;
  19. QT_TRY {
  20. //哇,终于来到大名鼎鼎的函数QCoreApplication::nofity()了 ==> Section 2-6
  21. returnValue = notify(receiver, event);
  22. } QT_CATCH (...) {
  23. --threadData->loopLevel;
  24. QT_RETHROW;
  25. }
  26. }
  27. // Section 2-6: $QTDIR\gui\kernel\qapplication.cpp
  28. // QCoreApplication::notify和它的重载函数QApplication::notify在Qt的派发过程中起到核心的作用,Qt的官方文档时这样说的:
  29. 任何线程的任何对象的所有事件在发送时都会调用notify函数。
  30. bool QApplication::notify(QObject *receiver, QEvent *e)
  31. {
  32. //代码很长,最主要的是一个大大的Switch,Case
  33. ..
  34. switch ( e->type())
  35. {
  36. ...
  37. case QEvent::MouseButtonPress:
  38. case QEvent::MouseButtonRelease:
  39. case QEvent::MouseButtonDblClick:
  40. case QEvent::MouseMove:
  41. ...
  42. //让自己私有类(d是私有类的句柄)来进一步处理 ==> Section 2-7
  43. res = d->notify_helper(w, w == receiver ? mouse : &me);
  44. e->spont = false;
  45. break;
  46. }
  47. ...
  48. }
  49. // Section 2-7: $QTDIR\gui\kernel\qapplication.cpp
  50. bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
  51. {
  52. ...
  53. // 向事件过滤器发送该事件,这里介绍一下Event Filters. 事件过滤器是一个接受即将发送给目标对象所有事件的对象。
  54. //如代码所示它开始处理事件在目标对象行动之前。过滤器的QObject::eventFilter()实现被调用,能接受或者丢弃过滤,
  55. 允许或者拒绝事件的更进一步的处理。如果所有的事件过滤器允许更进一步的事件处理,事件将被发送到目标对象本身。
  56. 如果他们中的一个停止处理,目标和任何后来的事件过滤器不能看到任何事件。
  57. if (sendThroughObjectEventFilters(receiver, e))
  58. return true;
  59. // 递交事件给receiver => Section 2-8
  60. bool consumed = receiver->event(e);
  61. e->spont = false;
  62. }
  63. // Section 2-8 $QTDIR\gui\kernel\qwidget.cpp
  64. // QApplication通过notify及其私有类notify_helper,将事件最终派发给了QObject的子类- QWidget.
  65. bool QWidget::event(QEvent *event)
  66. {
  67. ...
  68. switch(event->type()) {
  69. case QEvent::MouseButtonPress:
  70. // Don't reset input context here. Whether reset or not is
  71. // a responsibility of input method. reset() will be
  72. // called by mouseHandler() of input method if necessary
  73. // via mousePressEvent() of text widgets.
  74. #if 0
  75. resetInputContext();
  76. #endif
  77. //mousePressEvent是虚函数,QWidget的子类可以通过重载重新定义mousePress事件的行为
  78. mousePressEvent((QMouseEvent*)event);
  79. break;
  80. }

小结:Qt 事件处理机制 (下篇)的内容介绍完了,希望本文对你 有所帮助!更多相关资料请参考编辑推荐!

 

原创粉丝点击