sendEvent方法所属类为QCoreApplication,完整声明如下:
[static] bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event)
该方法的作用同样也是发布事件,但是与postEvent不同的是该方法仅能用本线程内的事件发送,不能用于跨线程的事件发布。
分析qt源码一个特别好的在线网站:
应该如何理解这个方法呢?我个人的理解是这个方法一个同步阻塞调用,说他同步是因为它内核的核心实现是通过直接函数调用来实现事件传递的,说他阻塞是因为必须要等待接收对象的event方法处理完成后才会返回,如果接收对象的event方法不返回,则会一直等待。
- inline bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event)
- {
- if (event)
- event->spont = false;
- return notifyInternal2(receiver, event);
- }
-
- bool QCoreApplication::notifyInternal2(QObject *receiver, QEvent *event)
- {
- bool selfRequired = QCoreApplicationPrivate::threadRequiresCoreApplication();
- ……
- if (!selfRequired)
- return doNotify(receiver, event);
- return self->notify(receiver, event);
- }
-
- bool QCoreApplication::notify(QObject *receiver, QEvent *event)
- {
- ……
- return doNotify(receiver, event);
- }
-
- static bool doNotify(QObject *receiver, QEvent *event)
- {
- ……
- return receiver->isWidgetType() ? false : QCoreApplicationPrivate::notify_helper(receiver, event);
- }
-
- bool QCoreApplicationPrivate::notify_helper(QObject *receiver, QEvent * event)
- {
- ……
- return receiver->event(event);
- }
通过上面的代码可以看到最终的调用是receiver->event(event);很明显这里是直接的函数调用实现的。