天下

记录修行的印记

[转]浅议Qt的事件处理机制二

浅议Qt的事件处理机制二
我们在上文中,介绍了Qt框架的事件处理机制:事件的产生、分发、接受和处理,并以视窗系统鼠标点击QWidget为例,对代码进行了剖析,向大家分析了Qt框架如何通过Event Loop处理进入处理消息队列循环,如何一步一步委派给平台相关的函数获取、打包用户输入事件交给视窗系统处理,函数调用栈如下:
    
QtCored4.dll
!QEventDispatcherWin32::processEvents()  qeventdispatcher_win.cpp Line 742    C++
QtGuid4.dll
!QGuiEventDispatcherWin32::processEvents()  Line 1202 + 0x15 bytes    C++
QtCored4.dll
!QEventLoop::processEvents()  Line 150    C++
QtCored4.dll
!QEventLoop::exec()  Line 204 + 0x2d bytes    C++
QtCored4.dll
!QCoreApplication::exec()  Line 1187 + 0x15 bytes    C++
QtGuid4.dll
!QApplication::exec()  Line 3813    C++
qt03.exe
!main()  Line 11 + 0x6 bytes    C++
qt03.exe
!WinMain()  Line 131 + 0x12 bytes    C++
qt03.exe
!__tmainCRTStartup()  Line 574 + 0x35 bytes    C
qt03.exe
!WinMainCRTStartup()  Line 399    C
kernel32.dll
!_BaseProcessStart@4()  + 0x23 bytes    
    
    

1.main(intchar **
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)

// (续上文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.
//打包翻译成功return true,否则false

bool QETWidget::translateMouseEvent(const MSG &msg)  
{  
    
//.. 这里很长的代码给以忽略   
    
    
    
//比如主窗口中有一个QPushButton,当在PushButton单击时,translateMouseEvent函数会计算出当前单击事件所在的的控件alienWidget,然后通过sendMouseEvent发送给当前到alienWidget!
     
    
//单击事件,计算出当前单击事件所在的的控件alienWidget
    state  = translateButtonState(msg.wParam, type, button); // button state
    const QPoint widgetPos = mapFromGlobal(QPoint(msg.pt.x, msg.pt.y));
    QWidget 
*alienWidget = !internalWinId() ? this : childAt(widgetPos);
    
    
    
//计算是否符合MouseButtonPress条件
    gpos = msg.pt;
    pos 
= mapFromGlobal(QPoint(gpos.x, gpos.y));

    
// mouse button pressed
    if (!qt_button_down && (type == QEvent::MouseButtonPress || type == QEvent::MouseButtonDblClick)) {
        QWidget 
*tlw = window();
        
if (QWidget *child = tlw->childAt(mapTo(tlw, pos)))
            qt_button_down 
= child;
        
else
            qt_button_down 
= this;
    }    
    
    
if (alienWidget && alienWidget->internalWinId())
        alienWidget 
= 0;
    
    
const QPoint globalPos(gpos.x,gpos.y);
    QWidget 
*widget = QApplicationPrivate::pickMouseReceiver(this, globalPos, pos, type,
                                                             Qt::MouseButtons(bs),
                                                             qt_button_down, alienWidget);
    
if (!widget)
        
return false// don't send event

    QMouseEvent e(type, pos, globalPos, Qt::MouseButton(button),
                  Qt::MouseButtons(state 
& Qt::MouseButtonMask),
                  Qt::KeyboardModifiers(state 
& Qt::KeyboardModifierMask));
            
       
      
// 让我们看一下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 7) Section 2-1:
QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) 
{
    
    
//如果我们通过EventFilter QCoreApplication::setEventFilter (EventFilter filter )设置了EventFilter
    
//将会调用我们设置的EventFilter
    
// send through app filter
    if (qApp->filterEvent(&msg, &res))
        
return res;    
   
   
//检查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 (eventevent->spont = truereturn 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 *= 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.   
        
//mousePressEvent是虚函数,QWidget的子类可以通过重载重新定义mousePress事件的行为   
        mousePressEvent((QMouseEvent*)event);  
        
break;     



/*!
    Sends \a message through the event filter that was set by
    setEventFilter(). If no event filter has been set, this function
    returns false; otherwise, this function returns the result of the
    event filter function in the \a result parameter.
    \sa setEventFilter()
*/
bool QCoreApplication::filterEvent(void *message, long *result)
{
    Q_D(QCoreApplication);
    
if (result)
        
*result = 0;
    
if (d->eventFilter)
        
return d->eventFilter(message, result);
#ifdef Q_OS_WIN
    
return winEventFilter(reinterpret_cast<MSG *>(message), result);
#else
    
return false;
#endif
}

posted on 2013-07-04 12:00 天下 阅读(2443) 评论(0)  编辑 收藏 引用 所属分类: QT


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2013年7月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

导航

统计

常用链接

留言簿(4)

随笔分类(378)

随笔档案(329)

链接

最新随笔

搜索

最新评论