1. 程式人生 > >Qt ------ 事件處理機制

Qt ------ 事件處理機制

後處理 分發 異步 ant ont 事件循環 tar rpo 基類

簡介

在Qt中,事件被封裝成一個個對象,所有的事件均繼承自抽象類QEvent。Qt是以事件驅動UI工具集。Signals/Slots在多線程中的實現也是依賴於Qt的事件處理機制。在Qt中,事件被封裝成一個個對象,所有的事件都繼承抽象基類QEvent。

Qt事件處理機制

產生事件:輸入設備,鍵盤鼠標等。keyPressEvent,keyReleaseEvent,mousePressEvent,mouseReleaseEvent事件(他們被封裝成QMouseEvent和QKeyEvent),這些事件來自於底層的操作系統,它們以異步的形式通知Qt事件處理系統,後文會仔細道來。當然Qt自己也會產生很多事件,比如QObject::startTimer()會觸發QTimerEvent。用戶的程序還可以自定義事件。

事件的接受和處理者:QObject類使整個Qt對象模型的核心,事件處理機制是QObject三大職責(內存管理、內省(intropection)與事件處理機制)之一。任何一個想要接受並處理事件的對象必須繼承QObject,可以選擇重載QObject::event()函數或事件的處理權轉交給父類。

事件的派送者:對於non-GUI的Qt程序,由QCoreApplication負責將QEvent分發給QObject的子類-Receiver;對於GUI程序,則由QApplication負責派送。

Qt源碼分析

Qt利用event loop從事件隊列中獲取用戶的輸入事件,並將事件轉義成QEvents,分發給相應的QObject處理,這中間共有七個階段。如下分析:

section 1

技術分享
#include <QApplication>     
#include "widget.h"    
int main(int argc, char *argv[])     
{         
        QApplication app(argc, argv); 
        Widget window;  // Widget 繼承自QWidget
        window.show();
        return app.exec(); // 進入Qpplication事件循環,見section 2
}
技術分享

section 2

技術分享
int QApplication::exec()
{
#ifndef QT_NO_ACCESSIBILITY
    QAccessible::setRootObject(qApp);
#endif    //簡單的交給QCoreApplication來處理事件循環=〉section 3
    return QCoreApplication::exec();
}
技術分享

section 3

技術分享
int QCoreApplication::exec()
{
    if (!QCoreApplicationPrivate::checkInstance("exec"))
        return -1;
    //得到當前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;
    }

    threadData->quitNow = false;
    QEventLoop eventLoop;
    self->d_func()->in_exec = true;
    self->d_func()->aboutToQuitEmitted = false;
       //委任QEventLoop 處理事件隊列循環 ==> Section 4
    int returnCode = eventLoop.exec();
    threadData->quitNow = false;
    if (self) {
        self->d_func()->in_exec = false;
        if (!self->d_func()->aboutToQuitEmitted)
            emit self->aboutToQuit();
        self->d_func()->aboutToQuitEmitted = true;
        sendPostedEvents(0, QEvent::DeferredDelete);
    }

    return returnCode;
}
技術分享

section 4

技術分享
int QEventLoop::exec(ProcessEventsFlags flags)
{
    Q_D(QEventLoop);  //訪問QEventloop私有類實例d
    //we need to protect from race condition with QThread::exit
    QMutexLocker locker(&static_cast<QThreadPrivate *>(QObjectPrivate::get(d->threadData->thread))->mutex);
    if (d->threadData->quitNow)
        return -1;

    if (d->inExec) {
        qWarning("QEventLoop::exec: instance %p has already called exec()", this);
        return -1;
    }
    d->inExec = true;
    d->exit = false;
    ++d->threadData->loopLevel;
    d->threadData->eventLoops.push(this);
    locker.unlock();

    // remove posted quit events when entering a new event loop
    QCoreApplication *app = QCoreApplication::instance();
    if (app && app->thread() == thread())
        QCoreApplication::removePostedEvents(app, QEvent::Quit);
    //這裏的實現代碼不少,最為重要的是以下幾行 
#if defined(QT_NO_EXCEPTIONS)
    while (!d->exit)
        processEvents(flags | WaitForMoreEvents | EventLoopExec);
#else
    try {
        while (!d->exit)  //只要沒有遇見exit,循環派發事件 
            processEvents(flags | WaitForMoreEvents | EventLoopExec);
    } catch (...) {
        qWarning("Qt has caught an exception thrown from an event handler. Throwing\n"
                 "exceptions from an event handler is not supported in Qt. You must\n"
                 "reimplement QApplication::notify() and catch all exceptions there.\n");

        // copied from below
        locker.relock();
        QEventLoop *eventLoop = d->threadData->eventLoops.pop();
        Q_ASSERT_X(eventLoop == this, "QEventLoop::exec()", "internal error");
        Q_UNUSED(eventLoop); // --release warning
        d->inExec = false;
        --d->threadData->loopLevel;

        throw;
    }
#endif

    // copied above
    locker.relock();
    QEventLoop *eventLoop = d->threadData->eventLoops.pop();
    Q_ASSERT_X(eventLoop == this, "QEventLoop::exec()", "internal error");
    Q_UNUSED(eventLoop); // --release warning
    d->inExec = false;
    --d->threadData->loopLevel;

    return d->returnCode;
}
技術分享

section 5

技術分享
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);  //將事件派發給與平臺相關的QAbstractEventDispatcher子類 =>Section 6
}
技術分享

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()) {
                // process queued socket events
                haveMessage = true;
                msg = d->queuedSocketEvents.takeFirst();  // 從處理socket隊列中取出一條事件,處理隊列裏面的socket事件
            } 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)) {
                    // queue user input events for later processing
                    haveMessage = false;
                    d->queuedUserInputEvents.append(msg);  // 用戶輸入事件入隊列,待以後處理 
                }
                if (haveMessage && (flags & QEventLoop::ExcludeSocketNotifiers)
                    && (msg.message == WM_QT_SOCKETNOTIFIER && msg.hwnd == d->internalHwnd)) {
                    // queue socket events for later processing
                    haveMessage = false;
                    d->queuedSocketEvents.append(msg);     // socket 事件入隊列,待以後處理   
                }
            }
            if (!haveMessage) {
                // no message - check for signalled objects
                for (int i=0; i<(int)nCount; i++)
                    pHandles[i] = d->winEventNotifierList.at(i)->handle();
                waitRet = MsgWaitForMultipleObjectsEx(nCount, pHandles, 0, QS_ALLINPUT, MWMO_ALERTABLE);
                if ((haveMessage = (waitRet == WAIT_OBJECT_0 + nCount))) {
                    // a new message has arrived, process it
                    continue;
                }
            }
            if (haveMessage) {
#ifdef Q_OS_WINCE
                // WinCE doesn‘t support hooks at all, so we have to call this by hand :(
                (void) qt_GetMessageHook(0, PM_REMOVE, (LPARAM) &msg);
#endif

                if (d->internalHwnd == msg.hwnd && msg.message == WM_QT_SENDPOSTEDEVENTS) {
                    if (seenWM_QT_SENDPOSTEDEVENTS) {
                        // when calling processEvents() "manually", we only want to send posted
                        // events once
                        needWM_QT_SENDPOSTEDEVENTS = true;
                        continue;
                    }
                    seenWM_QT_SENDPOSTEDEVENTS = true;
                } else if (msg.message == WM_TIMER) {
                    // avoid live-lock by keeping track of the timers we‘ve already sent
                    bool found = false;
                    for (int i = 0; !found && i < processedTimers.count(); ++i) {
                        const MSG processed = processedTimers.constData()[i];
                        found = (processed.wParam == msg.wParam && processed.hwnd == msg.hwnd && processed.lParam == msg.lParam);
                    }
                    if (found)
                        continue;
                    processedTimers.append(msg);
                } else if (msg.message == WM_QUIT) {
                    if (QCoreApplication::instance())
                        QCoreApplication::instance()->quit();
                    return false;
                }

                if (!filterEvent(&msg)) {
                    TranslateMessage(&msg);   //將事件打包成message調用Windows API派發出去
                    DispatchMessage(&msg);    //分發一個消息給窗口程序。消息被分發到回調函數,將消息傳遞給windows系統,windows處理完畢,會調用回調函數 => section 7 
                }
            } else if (waitRet < WAIT_OBJECT_0 + nCount) {
                d->activateEventNotifier(d->winEventNotifierList.at(waitRet - WAIT_OBJECT_0));
            } else {
                // nothing todo so break
                break;
            }
            retVal = true;
        }

        // still nothing - wait for message or signalled objects
        canWait = (!retVal
                   && !d->interrupt
                   && (flags & QEventLoop::WaitForMoreEvents));
        if (canWait) {
            DWORD nCount = d->winEventNotifierList.count();
            Q_ASSERT(nCount < MAXIMUM_WAIT_OBJECTS - 1);
            for (int i=0; i<(int)nCount; i++)
                pHandles[i] = d->winEventNotifierList.at(i)->handle();

            emit aboutToBlock();
            waitRet = MsgWaitForMultipleObjectsEx(nCount, pHandles, INFINITE, QS_ALLINPUT, MWMO_ALERTABLE | MWMO_INPUTAVAILABLE);
            emit awake();
            if (waitRet < WAIT_OBJECT_0 + nCount) {
                d->activateEventNotifier(d->winEventNotifierList.at(waitRet - WAIT_OBJECT_0));
                retVal = true;
            }
        }
    } while (canWait);

    if (!seenWM_QT_SENDPOSTEDEVENTS && (flags & QEventLoop::EventLoopExec) == 0) {
        // when called "manually", always send posted events
        QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
    }

    if (needWM_QT_SENDPOSTEDEVENTS)
        PostMessage(d->internalHwnd, WM_QT_SENDPOSTEDEVENTS, 0, 0);

    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);
         ...     
}
技術分享

section1~7的過程:Qt進入QApplication的event loop,經過層層委任,最終QEventLoop的processEvent將通過與平臺相關的AbstractEventDispatcher的子類QEventDispatcherWin32獲得用戶的輸入事件,並將其打包成message後,通過標準的Windows API傳遞給Windows OS。Windows OS得到通知後回調QtWndProc,至此事件的分發與處理完成了一半的路程。

事件的產生、分發、接受和處理,並以視窗系統鼠標點擊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),以下所有的討論都將嵌入在源碼之中。

技術分享
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)
技術分享

section 2-1 (section 8)

技術分享
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) { // in popup mode
            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);        // mouse event
        ...
}
技術分享

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(target, &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);
    else
        result = QApplication::sendEvent(receiver, event);
      
    ...
     
     return result;
}
技術分享

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;

    //哇,終於來到大名鼎鼎的函數QCoreApplication::nofity()了 ==> Section 2-6 
    QT_TRY {
        returnValue = notify(receiver, event);
    } QT_CATCH (...) {
        --threadData->loopLevel;
        QT_RETHROW;
    }

    ...

    return returnValue;
}
技術分享

section 2-6: $QTDIR\gui\kernel\qapplication.cpp

QCoreApplication::notify和它的重載函數QApplication::notify在Qt的派發過程中起到核心的作用,Qt的官方文檔時這樣說的:

任何線程的任何對象的所有事件在發送時都會調用notify函數。

技術分享
bool QCoreApplication::notify(QObject *receiver, QEvent *event)
{
    Q_D(QCoreApplication);
    // no events are delivered after ~QCoreApplication() has started
    if (QCoreApplicationPrivate::is_app_closing)
        return true;

    if (receiver == 0) {                        // serious error
        qWarning("QCoreApplication::notify: Unexpected null receiver");
        return true;
    }

#ifndef QT_NO_DEBUG
    d->checkReceiverThread(receiver);
#endif

    return receiver->isWidgetType() ? false : d->notify_helper(receiver, event);
}
技術分享

section 2-7: $QTDIR\gui\kernel\qapplication.cpp

notify 調用 notify_helper()

技術分享
bool QCoreApplicationPrivate::notify_helper(QObject *receiver, QEvent * event)
{
    // send to all application event filters
    if (sendThroughApplicationEventFilters(receiver, event))
        return true;
     // 向事件過濾器發送該事件,這裏介紹一下Event Filters. 事件過濾器是一個接受即將發送給目標對象所有事件的對象。 
    //如代碼所示它開始處理事件在目標對象行動之前。過濾器的QObject::eventFilter()實現被調用,能接受或者丟棄過濾
    //允許或者拒絕事件的更進一步的處理。如果所有的事件過濾器允許更進一步的事件處理,事件將被發送到目標對象本身。
    //如果他們中的一個停止處理,目標和任何後來的事件過濾器不能看到任何事件。
    if (sendThroughObjectEventFilters(receiver, event))
        return true;
    // deliver the event
    // 遞交事件給receiver  => Section 2-8 
    return receiver->event(event);
}
技術分享

section 2-8 $QTDIR\gui\kernel\qwidget.cpp

QApplication通過notify及其私有類notify_helper,將事件最終派發給了QObject的子類- QWidget.

技術分享
bool QWidget::event(QEvent *event)
{
    ...

    switch (event->type()) {
    case QEvent::MouseMove:
        mouseMoveEvent((QMouseEvent*)event);
        break;

    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((QMouseEvent*)event);
        break;

        ...

}
技術分享

Qt ------ 事件處理機制