1. 程式人生 > >Qt事件處理機制整個流程--以滑鼠在一個視窗中點選為例

Qt事件處理機制整個流程--以滑鼠在一個視窗中點選為例

轉載自:http://mobile.51cto.com/symbian-272812.htm,在此謝謝原作者的分享!

------------------------第一部分----------------------

 

本篇來介紹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.    
  65. // Section 6,QTDIR\src\corelib\kernel\qeventdispatcher_win.cpp     
  66. // 這段程式碼是完成與windows平臺相關的windows c++。 以跨平臺著稱的Qt同時也提供了對Symiban,Unix等平臺的訊息派發支援     
  67. // 其事現分別封裝在QEventDispatcherSymbian和QEventDispatcherUNIX     
  68. // QEventDispatcherWin32派生自QAbstractEventDispatcher.     
  69. bool QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags)     
  70. {     
  71.     Q_D(QEventDispatcherWin32);     
  72.     if (!d->internalHwnd)     
  73.         createInternalHwnd();     
  74.     d->interrupt = false;     
  75.     emit awake();     
  76.     bool canWait;     
  77.     bool retVal = false;     
  78.     bool seenWM_QT_SENDPOSTEDEVENTS = false;     
  79.     bool needWM_QT_SENDPOSTEDEVENTS = false;     
  80.     do {     
  81.         DWORD waitRet = 0;     
  82.         HANDLE pHandles[MAXIMUM_WAIT_OBJECTS - 1];     
  83.         QVarLengthArray<MSG> processedTimers;     
  84.         while (!d->interrupt) {     
  85.             DWORD nCount = d->winEventNotifierList.count();     
  86.             Q_ASSERT(nCount < MAXIMUM_WAIT_OBJECTS - 1);     
  87.             MSG msg;     
  88.             bool haveMessage;     
  89.             if (!(flags & QEventLoop::ExcludeUserInputEvents) && !d->queuedUserInputEvents.isEmpty()) {     
  90.                 // process queued user input events     
  91.                 haveMessage = true;     
  92.                 //從處理使用者輸入佇列中取出一條事件     
  93.                 msg = d->queuedUserInputEvents.takeFirst();     
  94.             } else if(!(flags & QEventLoop::ExcludeSocketNotifiers) && !d->queuedSocketEvents.isEmpty()) {     
  95.                 // 從處理socket佇列中取出一條事件     
  96.                 haveMessage = true;     
  97.                 msg = d->queuedSocketEvents.takeFirst();     
  98.             } else {     
  99.                 haveMessage = PeekMessage(&msg, 0, 0, 0, PM_REMOVE);     
  100.                 if (haveMessage && (flags & QEventLoop::ExcludeUserInputEvents)     
  101.                     && ((msg.message >= WM_KEYFIRST     
  102.                          && msg.message <= WM_KEYLAST)     
  103.                         || (msg.message >= WM_MOUSEFIRST     
  104.                             && msg.message <= WM_MOUSELAST)     
  105.                         || msg.message == WM_MOUSEWHEEL     
  106.                         || msg.message == WM_MOUSEHWHEEL     
  107.                         || msg.message == WM_TOUCH     
  108. #ifndef QT_NO_GESTURES     
  109.                         || msg.message == WM_GESTURE     
  110.                         || msg.message == WM_GESTURENOTIFY     
  111. #endif     
  112.                         || msg.message == WM_CLOSE)) {     
  113.                     // 使用者輸入事件入佇列,待以後處理     
  114.                     haveMessage = false;     
  115.                     d->queuedUserInputEvents.append(msg);     
  116.                 }     
  117.                 if (haveMessage && (flags & QEventLoop::ExcludeSocketNotifiers)     
  118.                     && (msg.message == WM_QT_SOCKETNOTIFIER && msg.hwnd == d->internalHwnd)) {     
  119.                     // socket 事件入佇列,待以後處理     
  120.                     haveMessage = false;     
  121.                     d->queuedSocketEvents.append(msg);     
  122.                 }     
  123.             }     
  124.             ....     
  125.                 if (!filterEvent(&msg)) {     
  126.                     TranslateMessage(&msg);     
  127.                     //將事件打包成message呼叫Windows API派發出去     
  128.                        //分發一個訊息給視窗程式。訊息被分發到回撥函式,將訊息傳遞給windows系統,windows處理完畢,會呼叫回撥函式 => section 7                         
  129.                   DispatchMessage(&msg);     
  130.                 }     
  131.             }                  
  132.         }     
  133.     } while (canWait);     
  134.       ...     
  135.     return retVal;     
  136. }    
  137.  
  138. // Section 7 windows視窗回撥函式 定義在QTDIR\src\gui\kernel\qapplication_win.cpp     
  139. extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)     
  140. {     
  141.    ...     
  142.    //將訊息重新封裝成QEvent的子類QMouseEvent ==> Section 8     
  143.     result = widget->translateMouseEvent(msg);         
  144.    ...     
  145. }     
  146.  

從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.  
  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  $QTDIR\src\gui\kernel\qapplication_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 $QTDIR\src\gui\kernel\qapplication.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. }    

 

 
  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.          
  12.     // 幾行程式碼對於Qt Jambi (QT Java繫結版本) 和QSA (QT Script for Application)的支援     
  13.      ...     
  14.      // 以下程式碼主要意圖為Qt強制事件只能夠傳送給當前執行緒裡的物件,也就是說receiver->d_func()->threadData應該等於QThreadData::current()。
  15.  注意,跨執行緒的事件需要藉助Event Loop來派發     
  16.      QObjectPrivate *d = receiver->d_func();     
  17.     QThreadData *threadData = d->threadData;     
  18.     ++threadData->loopLevel;     
  19.     bool returnValue;     
  20.     QT_TRY {     
  21.         //哇,終於來到大名鼎鼎的函式QCoreApplication::nofity()了 ==> Section 2-6     
  22.         returnValue = notify(receiver, event);     
  23.     } QT_CATCH (...) {     
  24.         --threadData->loopLevel;     
  25.         QT_RETHROW;     
  26.     }     
  27. }     
  28. // Section 2-6:  $QTDIR\gui\kernel\qapplication.cpp     
  29. // QCoreApplication::notify和它的過載函式QApplication::notify在Qt的派發過程中起到核心的作用,Qt的官方文件時這樣說的:
  30. 任何執行緒的任何物件的所有事件在傳送時都會呼叫notify函式。     
  31. bool QApplication::notify(QObject *receiver, QEvent *e)     
  32. {     
  33.    //程式碼很長,最主要的是一個大大的Switch,Case     
  34.    ..     
  35.    switch ( e->type())     
  36.    {     
  37.     ...     
  38.     case QEvent::MouseButtonPress:     
  39.     case QEvent::MouseButtonRelease:     
  40.     case QEvent::MouseButtonDblClick:     
  41.     case QEvent::MouseMove:     
  42.      ...     
  43.         //讓自己私有類(d是私有類的控制代碼)來進一步處理 ==> Section 2-7     
  44.         res = d->notify_helper(w, w == receiver ? mouse : &me);     
  45.         e->spont = false;     
  46.         break;     
  47.     }     
  48.     ...     
  49. }     
  50. // Section 2-7:  $QTDIR\gui\kernel\qapplication.cpp     
  51. bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)     
  52. {     
  53.     ...     
  54.     // 向事件過濾器傳送該事件,這裡介紹一下Event Filters. 事件過濾器是一個接受即將傳送給目標物件所有事件的物件。     
  55.    //如程式碼所示它開始處理事件在目標物件行動之前。過濾器的QObject::eventFilter()實現被呼叫,能接受或者丟棄過濾,
  56. 允許或者拒絕事件的更進一步的處理。如果所有的事件過濾器允許更進一步的事件處理,事件將被髮送到目標物件本身。
  57. 如果他們中的一個停止處理,目標和任何後來的事件過濾器不能看到任何事件。     
  58.     if (sendThroughObjectEventFilters(receiver, e))     
  59.         return true;     
  60.      // 遞交事件給receiver  => Section 2-8     
  61.     bool consumed = receiver->event(e);     
  62.     e->spont = false;     
  63. }     
  64. // Section 2-8  $QTDIR\gui\kernel\qwidget.cpp     
  65. // QApplication通過notify及其私有類notify_helper,將事件最終派發給了QObject的子類- QWidget.     
  66. bool QWidget::event(QEvent *event)     
  67. {     
  68.     ...     
  69.     switch(event->type()) {     
  70.     case QEvent::MouseButtonPress:     
  71.         // Don't reset input context here. Whether reset or not is     
  72.         // a responsibility of input method. reset() will be     
  73.         // called by mouseHandler() of input method if necessary     
  74.         // via mousePressEvent() of text widgets.     
  75. #if 0     
  76.         resetInputContext();     
  77. #endif     
  78.         //mousePressEvent是虛擬函式,QWidget的子類可以通過過載重新定義mousePress事件的行為     
  79.         mousePressEvent((QMouseEvent*)event);     
  80.         break;        
  81. }   

小結:Qt 事件處理機制 (下篇)的內容介紹完了,希望本文對你 有所幫助!更多相關資料請參考編輯推薦!

注:轉載時刪除了原文中一些重複的地方。