剖析Qt 事件的產生、分發、接受、處理流程
阿新 • • 發佈:2018-12-29
Windows上Qt事件處理機制詳解:
1、誰來產生事件: 最容易想到的是我們的輸入裝置,比如鍵盤、滑鼠產生的
keyPressEvent,keyReleaseEvent,mousePressEvent,mouseReleaseEvent事件(他們被封裝成QMouseEvent和QKeyEvent),這些事件來自於底層的作業系統,它們以非同步的形式通知Qt事件處理系統,後文會仔細道來。當然Qt自己也會產生很多事件,比如QObject::startTimer()會觸發QTimerEvent. 使用者的程式還可以自己定製事件。
2、誰來接受和處理事件:答案是QObject。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" //Section 1 int main(int argc, char *argv[]) { QApplication app(argc, argv); Widget window; // Widget 繼承自QWidget window.show(); return app.exec(); // 進入QApplication事件迴圈,見section 2 } <span style="font-family: Arial, Helvetica, sans-serif;"> </span>
從Section 1~Section7, Qt進入QApplication的event loop,經過層層委任,最終QEventloop的processEvent將通過與平臺相關的QAbstractEventDispatcher的子類QEventDispatcherWin32獲得使用者的使用者輸入事件,並將其打包成message後,通過標準Windows API ,把訊息傳遞給了Windows OS,Windows OS得到通知後回撥QtWndProc, 至此事件的分發與處理完成了一半的路程。// Section 2: int QApplication::exec() { //skip codes //簡單的交給QCoreApplication來處理事件迴圈=〉section 3 return QCoreApplication::exec(); } // Section 3 int QCoreApplication::exec() { //得到當前Thread資料,確保在同一個執行緒 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; } //檢查event loop是否已經建立 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; //委任QEventLoop 處理事件佇列迴圈 ==> Section 4 int returnCode = eventLoop.exec(); .... } return returnCode; } // Section 4 int QEventLoop::exec(ProcessEventsFlags flags) { //這裡的實現程式碼不少,最為重要的是以下幾行 Q_D(QEventLoop); // 訪問QEventloop私有類例項d try { //只要沒有遇見exit,迴圈派發事件 while (!d->exit) processEvents(flags | WaitForMoreEvents | EventLoopExec); } catch (...) {} } // Section 5 bool QEventLoop::processEvents(ProcessEventsFlags flags) { Q_D(QEventLoop); if (!d->threadData->eventDispatcher) return false; if (flags & DeferredDeletion) QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete); //將事件派發給與平臺相關的QAbstractEventDispatcher子類 =>Section 6 return d->threadData->eventDispatcher->processEvents(flags); } // Section 6,QTDIR\src\corelib\kernel\qeventdispatcher_win.cpp // 這段程式碼是完成與windows平臺相關的windows c++。 以跨平臺著稱的Qt同時也提供了對Symiban,Unix等平臺的訊息派發支援 // 其事現分別封裝在QEventDispatcherSymbian和QEventDispatcherUNIX // QEventDispatcherWin32派生自QAbstractEventDispatcher. 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()) { // process queued user input events haveMessage = true; //從處理使用者輸入佇列中取出一條事件 msg = d->queuedUserInputEvents.takeFirst(); } else if(!(flags & QEventLoop::ExcludeSocketNotifiers) && !d->queuedSocketEvents.isEmpty()) { // 從處理socket佇列中取出一條事件 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)) { // socket 事件入佇列,待以後處理 haveMessage = false; d->queuedSocketEvents.append(msg); } } .... if (!filterEvent(&msg)) { TranslateMessage(&msg); //將事件打包成message呼叫Windows API派發出去 //分發一個訊息給視窗程式。訊息被分發到回撥函式,將訊息傳遞給windows系統,windows處理完畢,會呼叫回撥函式 => section 7 DispatchMessage(&msg); } } } } while (canWait); ... return retVal; } // Section 7 windows視窗回撥函式 定義在QTDIR\src\gui\kernel\qapplication_win.cpp extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { ... //將訊息重新封裝成QEvent的子類QMouseEvent ==> Section 8 result = widget->translateMouseEvent(msg); ... }
// (續上文Section 7) Section 2-1:
QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
...
//檢查message是否屬於Qt可轉義的滑鼠事件
if (qt_is_translatable_mouse_event(message)) {
if (QApplication::activePopupWidget() != 0) {
POINT curPos = msg.pt;
//取得滑鼠點選座標所在的QWidget指標,它指向我們在main建立的widget例項
QWidget* w = QApplication::widgetAt(curPos.x, curPos.y);
if (w)
widget = (QETWidget*)w;
}
if (!qt_tabletChokeMouse) {
//對,就在這裡。Windows的回撥函式將滑鼠事件分發回給了Qt Widget
// => Section 2-2
result = widget->translateMouseEvent(msg);
...
}
// Section 2-2 $QTDIR\src\gui\kernel\qapplication_win.cpp
//該函式所在與Windows平臺相關,主要職責就是把已windows格式打包的滑鼠事件解包、翻譯成QApplication可識別的QMouseEvent,QWidget.
bool QETWidget::translateMouseEvent(const MSG &msg)
{
//.. 這裡很長的程式碼給以忽略
// 讓我們看一下sendMouseEvent的宣告
// widget是事件的接受者; e是封裝好的QMouseEvent
// ==> Section 2-3
res = QApplicationPrivate::sendMouseEvent(widget, &e, alienWidget, this, &qt_button_down, qt_last_mouse_receiver);
}
// Section 2-3 $QTDIR\src\gui\kernel\qapplication.cpp
bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
QWidget *alienWidget, QWidget *nativeWidget,
QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,
bool spontaneous)
{
//至此與平臺相關程式碼處理完畢
//MouseEvent預設的傳送方式是spontaneous, 所以將執行sendSpontaneousEvent。 sendSpontaneousEvent() 與 sendEvent的程式碼實現幾乎相同,
除了將QEvent的屬性spontaneous標記不同。 這裡是解釋什麼spontaneous事件:如果事件由應用程式之外產生的,比如一個系統事件。
顯然MousePress事件是由視窗系統產生的一個的事件(詳見上文Section 1~ Section 7),因此它是 spontaneous事件
if (spontaneous)
result = QApplication::sendSpontaneousEvent(receiver, event); ==〉Section 2-4
else
result = QApplication::sendEvent(receiver, event);
}
// Section 2-4 C:\Qt\4.7.1-Vs\src\corelib\kernel\qcoreapplication.h
inline bool QCoreApplication::sendSpontaneousEvent(QObject *receiver, QEvent *event)
{
//將event標記為自發事件
//進一步呼叫 2-5 QCoreApplication::notifyInternal
if (event) event->spont = true; return self ? self->notifyInternal(receiver, event) : false;
}
// Section 2-5: $QTDIR\gui\kernel\qapplication.cpp
bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event)
{
// 幾行程式碼對於Qt Jambi (QT Java繫結版本) 和QSA (QT Script for Application)的支援
...
// 以下程式碼主要意圖為Qt強制事件只能夠傳送給當前執行緒裡的物件,也就是說receiver->d_func()->threadData應該等於QThreadData::current()。
注意,跨執行緒的事件需要藉助Event Loop來派發
QObjectPrivate *d = receiver->d_func();
QThreadData *threadData = d->threadData;
++threadData->loopLevel;
bool returnValue;
QT_TRY {
//哇,終於來到大名鼎鼎的函式QCoreApplication::nofity()了 ==> Section 2-6
returnValue = notify(receiver, event);
} QT_CATCH (...) {
--threadData->loopLevel;
QT_RETHROW;
}
}
// Section 2-6: $QTDIR\gui\kernel\qapplication.cpp
// QCoreApplication::notify和它的過載函式QApplication::notify在Qt的派發過程中起到核心的作用,Qt的官方文件時這樣說的:
任何執行緒的任何物件的所有事件在傳送時都會呼叫notify函式。
bool QApplication::notify(QObject *receiver, QEvent *e)
{
//程式碼很長,最主要的是一個大大的Switch,Case
..
switch ( e->type())
{
...
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::MouseMove:
...
//讓自己私有類(d是私有類的控制代碼)來進一步處理 ==> Section 2-7
res = d->notify_helper(w, w == receiver ? mouse : &me);
e->spont = false;
break;
}
...
}
// Section 2-7: $QTDIR\gui\kernel\qapplication.cpp
bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
{
...
// 向事件過濾器傳送該事件,這裡介紹一下Event Filters. 事件過濾器是一個接受即將傳送給目標物件所有事件的物件。
//如程式碼所示它開始處理事件在目標物件行動之前。過濾器的QObject::eventFilter()實現被呼叫,能接受或者丟棄過濾,
允許或者拒絕事件的更進一步的處理。如果所有的事件過濾器允許更進一步的事件處理,事件將被髮送到目標物件本身。
如果他們中的一個停止處理,目標和任何後來的事件過濾器不能看到任何事件。
if (sendThroughObjectEventFilters(receiver, e))
return true;
// 遞交事件給receiver => Section 2-8
bool consumed = receiver->event(e);
e->spont = false;
}
// Section 2-8 $QTDIR\gui\kernel\qwidget.cpp
// QApplication通過notify及其私有類notify_helper,將事件最終派發給了QObject的子類- QWidget.
bool QWidget::event(QEvent *event)
{
...
switch(event->type()) {
case QEvent::MouseButtonPress:
// Don't reset input context here. Whether reset or not is
// a responsibility of input method. reset() will be
// called by mouseHandler() of input method if necessary
// via mousePressEvent() of text widgets.
#if 0
resetInputContext();
#endif
//mousePressEvent是虛擬函式,QWidget的子類可以通過過載重新定義mousePress事件的行為
mousePressEvent((QMouseEvent*)event);
break;
}
- main(int, char **)
- QApplication::exec()
- QCoreApplication::exec()
- QEventLoop::exec(ProcessEventsFlags )
- QEventLoop::processEvents(ProcessEventsFlags )
- QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags)
- QT_WIN_CALLBACK QtWndProc(HWND hwnd, 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)