Qt之sendEvent


基本介绍

sendEvent方法所属类为QCoreApplication,完整声明如下:

[static] bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event)

该方法的作用同样也是发布事件,但是与postEvent不同的是该方法仅能用本线程内的事件发送,不能用于跨线程的事件发布。

分析qt源码一个特别好的在线网站:

qt5在线源码

理解

应该如何理解这个方法呢?我个人的理解是这个方法一个同步阻塞调用,说他同步是因为它内核的核心实现是通过直接函数调用来实现事件传递的,说他阻塞是因为必须要等待接收对象的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);很明显这里是直接的函数调用实现的。

使用要点

  • 使用sendEvent方法可以使用局部变量,也可以使用堆申请的变量,但是需要自己释放内存,否则将会产生内存泄露。
  • 这一个用于本线程间的发送事件用到的方法
  • 对于postEvent方法发送的事件到对应线程的事件队列后,最终也是通过调用sendEvent方法来发送对象的。

猜你喜欢

转载自blog.csdn.net/iqanchao/article/details/132790790