检测到“我正在跑步".在Qt GUI事件线程中

编程入门 行业动态 更新时间:2024-10-11 21:32:25
本文介绍了检测到“我正在跑步".在Qt GUI事件线程中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我具有此功能来更新一些GUI内容:

I have this function to update some GUI stuff:

void SavedConnections::renderList() { // Do GUI stuff! Must run in Qt thread!!! ... }

我需要确保不从其他线程调用此函数.我计划要做的是将其推迟到事件循环中并发出警告:

I need to ensure that this function isn't called from other threads. What I plan to do is to defer it into event loop and raise a warning:

void SavedConnections::renderList() { if(!this_thread_is_Qt_GUI_thread()) { qDebug()<< "Warning: GUI operation attempted from non GUI thread!\n"; QCoreApplication::postEvent(this, new UpdateGUIEvent()); return; } // Do GUI stuff! Must run in Qt thread!!! ... }

此模式也非常方便,使方法可以保证在GUI线程中异步运行而无需任何难看的语法. 我已经问过有关Java的ExecutorService的类似问题.

This pattern is also very convenient to make methods that are guaranteed to run asynchronously in GUI thread without any ugly syntax. I already asked similar question about Java's ExecutorService.

推荐答案

您可以检查当前线程是否是对象所在的线程:

You can check if the current thread is the thread your object lives in:

if (QThread::currentThread() != this->thread()) { // Called from different thread }

请注意,这可能不是主GUI线程!它是this所在的线程(请参见 QObject线程相似性)

Note that this might not be the main GUI-Thread! It is the thread this lives in (see QObject Thread affinity). If you don't change it using QObject::moveToThread, it is the thread the object was created in.

这也是QCoreApplication::postEvent用于确定将事件发布到哪个线程的方法.目标线程必须运行QEventLoop才能响应事件.

This is also what QCoreApplication::postEvent uses to determine into which thread the event should be posted. The targeted Thread must run a QEventLoop to respond to the event.

因此,如果对象不在主GUI线程中,则检查主GUI线程(qApp->thread()),但将其发布到this的线程可能不起作用.但是,如果在那里进行GUI处理,则无论如何它都应该存在于GUI线程中

So checking for the main-GUI-Thread (qApp->thread()), but posting to this's thread might not work, if your object does not live in the main-GUI-Thread. However, if you do GUI stuff there, it should anyway live in the GUI-Thread

更多推荐

检测到“我正在跑步".在Qt GUI事件线程中

本文发布于:2023-11-12 13:18:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581618.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   检测到   事件   Qt   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!