Qt:使用线程和信号/插槽时,GUI有时会冻结 [英] Qt: GUI sometimes freezing when using threads and signals/slots

查看:80
本文介绍了Qt:使用线程和信号/插槽时,GUI有时会冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个(替代)函数处理传感器提供的数据.函数在其自己的线程中运行,并在结果准备好时发出信号.该信号连接到UI小部件的插槽,以显示结果. 使用其中一项功能,效果很好.但是,当使用另一个时,GUI开始滞后并很快冻结.

I have two (alternative) functions working on data supplied by a sensor. The functions run in their own thread and emit a signal when the result is ready. This signal is connected to a slot of a UI widget, displaying the result. With one of the functions, this works well. When using the other however, the GUI starts to lag and soon freezes.

QDebug显示数据仍在处理中.

QDebug shows that data is still being processed though.

在GUI线程中运行代码时,没有问题.

When running the code in the GUI-thread, there is no problem.

问题可能在于工作线程生成数据的速度快于UI绘制数据的速度,由于Qt :: QueuedConnection而导致一些滞后吗?如果是这样,我有什么选择?如果没有,我还能检查什么?

Might the problem be that the worker-thread produces data faster than the UI can draw it, leading to some lag due to the Qt::QueuedConnection? If so, what alternatives do I have? If not, what else can I check?

推荐答案

工作线程似乎在向UI线程发送垃圾邮件,填满了主事件循环,因此GUI事件很难处理.

It would appear that the worker thread is spamming the UI thread, filling up the main event loop so that GUI events have a hard time getting processed.

在工作线程中看不到某些代码,很难推荐解决方案.在一天结束时,您只想按指定的时间间隔发出信号.

Without seeing some of the code in the worker thread, it is difficult to recommend a solution. At the end of the day, you only want to emit your signal at specified intervals.

您可能对QTime类有些运气.每次发射信号时,调用QTime::start,然后检查QTime::elapsed值.仅当它超过某个特定阈值时,才发出信号并重置计时器.

You may have some luck with the QTime class. Each time your signal is emitted, call QTime::start and then check the QTime::elapsed value. Only when it is above a certain threshold emit your signal and reset the timer.

如果您可以丢弃中间传感器值,那是理想的选择.如果全部需要它们,则必须将它们添加到QVector或其他内容中,然后在信号中一次将它们全部发送出去.

If you can throw away the intermediate sensor values, that's ideal. If you need them all, you would have to add them to a QVector or something and send them all at once in the signal.

更好的是,如果您只能定期轮询传感器本身. QTimer类在这种情况下可能很有用-使其在每次滴答"时都轮询传感器(并发出信号).

Even better is if you can only poll the sensor itself at regular intervals. The QTimer class might be useful in this case--have it poll the sensor (and emit the signal) every time it "ticks".

  • http://doc.qt.nokia.com/latest/qtime.htm
  • http://doc.qt.nokia.com/latest/qtimer.htm

这篇关于Qt:使用线程和信号/插槽时,GUI有时会冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆