【转】Qt 事件处理机制 (下篇)

转自:http://mobile.51cto.com/symbian-272816.htm

在Qt中,事件被封装成一个个对象,所有的事件均继承自抽象类QEvent. 接下来依次谈谈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  
  9 // (续上文Section 7) Section 2-1:     
 10 QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)      
 11 {     
 12    ...     
 13    //检查message是否属于Qt可转义的鼠标事件     
 14    if (qt_is_translatable_mouse_event(message)) {     
 15         if (QApplication::activePopupWidget() != 0) {                 
 16             POINT curPos = msg.pt;     
 17             //取得鼠标点击坐标所在的QWidget指针,它指向我们在main创建的widget实例     
 18             QWidget* w = QApplication::widgetAt(curPos.x, curPos.y);     
 19             if (w)     
 20                 widget = (QETWidget*)w;     
 21         }     
 22         if (!qt_tabletChokeMouse) {     
 23             //对,就在这里。Windows的回调函数将鼠标事件分发回给了Qt Widget      
 24             // => Section 2-2     
 25             result = widget->translateMouseEvent(msg);            
 26      ...     
 27 }     
 28 // Section 2-2  $QTDIRsrcguikernelqapplication_win.cpp     
 29 //该函数所在与Windows平台相关,主要职责就是把已windows格式打包的鼠标事件解包、翻译成QApplication可识别的QMouseEvent,QWidget.     
 30 bool QETWidget::translateMouseEvent(const MSG &msg)     
 31 {     
 32      //.. 这里很长的代码给以忽略       
 33       // 让我们看一下sendMouseEvent的声明     
 34      // widget是事件的接受者; e是封装好的QMouseEvent     
 35      // ==> Section 2-3     
 36      res = QApplicationPrivate::sendMouseEvent(widget, &e, alienWidget, this, &qt_button_down, qt_last_mouse_receiver);     
 37 }     
 38 // Section 2-3 $QTDIRsrcguikernelqapplication.cpp     
 39 bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,     
 40                                          QWidget *alienWidget, QWidget *nativeWidget,     
 41                                          QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,     
 42                                          bool spontaneous)     
 43 {     
 44      //至此与平台相关代码处理完毕     
 45      //MouseEvent默认的发送方式是spontaneous, 所以将执行sendSpontaneousEvent。 sendSpontaneousEvent() 与 sendEvent的代码实现几乎相同,
 46                    除了将QEvent的属性spontaneous标记不同。 这里是解释什么spontaneous事件:如果事件由应用程序之外产生的,比如一个系统事件。 
 47                显然MousePress事件是由视窗系统产生的一个的事件(详见上文Section 1~ Section 7),因此它是   spontaneous事件     
 48        
 49     if (spontaneous)     
 50         result = QApplication::sendSpontaneousEvent(receiver, event);  ==〉Section 2-4     
 51     else    
 52         result = QApplication::sendEvent(receiver, event);     
 53 }    
 54 
 55 // Section 2-4 C:Qt4.7.1-Vssrccorelibkernelqcoreapplication.h     
 56 inline bool QCoreApplication::sendSpontaneousEvent(QObject *receiver, QEvent *event)     
 57 {      
 58     //将event标记为自发事件     
 59      //进一步调用 2-5 QCoreApplication::notifyInternal     
 60     if (event) event->spont = true; return self ? self->notifyInternal(receiver, event) : false;      
 61 }     
 62 // Section 2-5:  $QTDIRguikernelqapplication.cpp     
 63 bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event)     
 64 {     
 65          
 66     // 几行代码对于Qt Jambi (QT Java绑定版本) 和QSA (QT Script for Application)的支持     
 67      ...     
 68      // 以下代码主要意图为Qt强制事件只能够发送给当前线程里的对象,也就是说receiver->d_func()->threadData应该等于QThreadData::current()。
 69                                           注意,跨线程的事件需要借助Event Loop来派发     
 70      QObjectPrivate *d = receiver->d_func();     
 71     QThreadData *threadData = d->threadData;     
 72     ++threadData->loopLevel;     
 73     bool returnValue;     
 74     QT_TRY {     
 75         //哇,终于来到大名鼎鼎的函数QCoreApplication::nofity()了 ==> Section 2-6     
 76         returnValue = notify(receiver, event);     
 77     } QT_CATCH (...) {     
 78         --threadData->loopLevel;     
 79         QT_RETHROW;     
 80     }     
 81 }     
 82 // Section 2-6:  $QTDIRguikernelqapplication.cpp     
 83 // QCoreApplication::notify和它的重载函数QApplication::notify在Qt的派发过程中起到核心的作用,Qt的官方文档时这样说的:
 84                                                        任何线程的任何对象的所有事件在发送时都会调用notify函数。     
 85 bool QApplication::notify(QObject *receiver, QEvent *e)     
 86 {     
 87    //代码很长,最主要的是一个大大的Switch,Case     
 88    ..     
 89    switch ( e->type())     
 90    {     
 91     ...     
 92     case QEvent::MouseButtonPress:     
 93     case QEvent::MouseButtonRelease:     
 94     case QEvent::MouseButtonDblClick:     
 95     case QEvent::MouseMove:     
 96      ...     
 97         //让自己私有类(d是私有类的句柄)来进一步处理 ==> Section 2-7     
 98         res = d->notify_helper(w, w == receiver ? mouse : &me);     
 99         e->spont = false;     
100         break;     
101     }     
102     ...     
103 }     
104 // Section 2-7:  $QTDIRguikernelqapplication.cpp     
105 bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)     
106 {     
107     ...     
108     // 向事件过滤器发送该事件,这里介绍一下Event Filters. 事件过滤器是一个接受即将发送给目标对象所有事件的对象。     
109    //如代码所示它开始处理事件在目标对象行动之前。过滤器的QObject::eventFilter()实现被调用,能接受或者丢弃过滤,
110                          允许或者拒绝事件的更进一步的处理。如果所有的事件过滤器允许更进一步的事件处理,事件将被发送到目标对象本身。
111                          如果他们中的一个停止处理,目标和任何后来的事件过滤器不能看到任何事件。     
112     if (sendThroughObjectEventFilters(receiver, e))     
113         return true;     
114      // 递交事件给receiver  => Section 2-8     
115     bool consumed = receiver->event(e);     
116     e->spont = false;     
117 }     
118 // Section 2-8  $QTDIRguikernelqwidget.cpp     
119 // QApplication通过notify及其私有类notify_helper,将事件最终派发给了QObject的子类- QWidget.     
120 bool QWidget::event(QEvent *event)     
121 {     
122     ...     
123     switch(event->type()) {     
124     case QEvent::MouseButtonPress:     
125         // Don't reset input context here. Whether reset or not is     
126         // a responsibility of input method. reset() will be     
127         // called by mouseHandler() of input method if necessary     
128         // via mousePressEvent() of text widgets.     
129 #if 0     
130         resetInputContext();     
131 #endif     
132         //mousePressEvent是虚函数,QWidget的子类可以通过重载重新定义mousePress事件的行为     
133         mousePressEvent((QMouseEvent*)event);     
134         break;        
135 }   
原文地址:https://www.cnblogs.com/aheng123/p/5588913.html