Qt 事件处理机制

Posted 云水

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt 事件处理机制相关的知识,希望对你有一定的参考价值。

Qt 事件处理机制

 

因为这篇文章写得特别好,将Qt的事件处理机制能够阐述的清晰有条理,并且便于学习。于是就装载过来了(本文做了排版,并删减了一些冗余的东西,希望原主勿怪),以供学习之用。

简介

在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 事件处理机制的主要内容,如果未能解决你的问题,请参考以下文章

Qt ------ 事件处理机制

QT开发——QT事件处理机制

9Qt 事件处理机制

转解读Qt 事件处理机制(上篇)

Qt事件机制(是动作发生后,一种通知对象的消息,是被动与主动的总和。先处理自己队列中的消息,然后再处理系统消息队列中的消息)

Python Qt GUI设计:5种事件处理机制(提升篇—3)