Calarence 2024-08-05 19:38 采纳率: 11.1%
浏览 18
已结题

Qt 次线程发给UI线程的信号槽函数没有执行

问题描述:
Qt下次线程发送信号,UI线程槽函数执行,在大多数情况下,emit之后,槽函数都会执行。但是存在偶然不响应槽函数的情况。
其中,UI线程添加了远程桌面插件QAxWidget,执行步骤如下:

  1. 点击QAxWidget中远程桌面的软件界面中的按钮;
  2. 按钮通过TCPSocket发送命令;
  3. 次线程解析命令,emit发送消息;
  4. UI线程执行槽函数。

通过记录日志发现,槽函数有时候没有执行。(看上去像是UI线程没有去处理消息队列了)
所以,在UI线程建立一个1秒的定时器,定时器的timeout槽函数啥也不干,结果调试发现,次线程发过来的消息,槽函数都能响应了。
非常令人费解:
1.如果UI线程休眠了,那为什么建立的定时器timeout槽函数可以响应?
2.次线程和UI线程的信号槽,如何确保每一次槽函数都能被执行?

  • 写回答

2条回答 默认 最新

  • 火花20180731 2024-08-06 10:52
    关注

    有两个问题,首先你这个TCPSocket收到指令了么,其次你这个次线程有没有自己的事件循环,如果你的次线程有自己的事件循环,则信号事件不走QApplication::exec()事件循环,那么信号相当于并没有发出来
    moveToThread和QThread::run里调用exec可以创建线程自己的事件循环,如果信号要外发,则需要做一些转接操作。
    Qt开发手册:
    A QObject instance is said to have a thread affinity, or that it lives in a certain thread. When a QObject receives a queued signal or a posted event, the slot or event handler will run in the thread that the object lives in.
    Note: If a QObject has no thread affinity (that is, if thread() returns zero), or if it lives in a thread that has no running event loop, then it cannot receive queued signals or posted events.
    By default, a QObject lives in the thread in which it is created. An object's thread affinity can be queried using thread() and changed using moveToThread().
    All QObjects must live in the same thread as their parent. Consequently:
    setParent() will fail if the two QObjects involved live in different threads.
    When a QObject is moved to another thread, all its children will be automatically moved too.
    moveToThread() will fail if the QObject has a parent.
    If QObjects are created within QThread::run(), they cannot become children of the QThread object because the QThread does not live in the thread that calls QThread::run().
    Note: A QObject's member variables do not automatically become its children. The parent-child relationship must be set by either passing a pointer to the child's constructor, or by calling setParent(). Without this step, the object's member variables will remain in the old thread when moveToThread() is called.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 8月16日
  • 已采纳回答 8月8日
  • 创建了问题 8月5日

悬赏问题

  • ¥15 依据报错在原代吗格式的基础上解决问题
  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?