• Qt之sendEvent



    基本介绍

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

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

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

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

    qt5在线源码

    理解

    应该如何理解这个方法呢?我个人的理解是这个方法一个同步阻塞调用,说他同步是因为它内核的核心实现是通过直接函数调用来实现事件传递的,说他阻塞是因为必须要等待接收对象的event方法处理完成后才会返回,如果接收对象的event方法不返回,则会一直等待。

    源码分析

    1. inline bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event)
    2. {
    3. if (event)
    4. event->spont = false;
    5. return notifyInternal2(receiver, event);
    6. }
    7. bool QCoreApplication::notifyInternal2(QObject *receiver, QEvent *event)
    8. {
    9. bool selfRequired = QCoreApplicationPrivate::threadRequiresCoreApplication();
    10. ……
    11. if (!selfRequired)
    12. return doNotify(receiver, event);
    13. return self->notify(receiver, event);
    14. }
    15. bool QCoreApplication::notify(QObject *receiver, QEvent *event)
    16. {
    17. ……
    18. return doNotify(receiver, event);
    19. }
    20. static bool doNotify(QObject *receiver, QEvent *event)
    21. {
    22. ……
    23. return receiver->isWidgetType() ? false : QCoreApplicationPrivate::notify_helper(receiver, event);
    24. }
    25. bool QCoreApplicationPrivate::notify_helper(QObject *receiver, QEvent * event)
    26. {
    27. ……
    28. return receiver->event(event);
    29. }

    通过上面的代码可以看到最终的调用是receiver->event(event);很明显这里是直接的函数调用实现的。

    使用要点

    • 使用sendEvent方法可以使用局部变量,也可以使用堆申请的变量,但是需要自己释放内存,否则将会产生内存泄露。
    • 这一个用于本线程间的发送事件用到的方法
    • 对于postEvent方法发送的事件到对应线程的事件队列后,最终也是通过调用sendEvent方法来发送对象的。
  • 相关阅读:
    鉴源论坛丨信号基础设备概述
    Win10如何用管理员身份运行Windows终端?
    系统架构与Tomcat的安装和配置
    电脑如何在网页上下载视频 浏览器如何下载网页视频
    New Crack:::CAD .NET 14.1.X
    网络安全(黑客)自学
    【RuoYi-Cloud-Plus】学习笔记 05 - Spring Cloud Gateway(一)关于配置文件参数
    论文精读:GHM:Gradient Harmonized Single-stage Detector
    D. Meta-set #824 div2
    std::bind 源码分析
  • 原文地址:https://blog.csdn.net/iqanchao/article/details/132790790