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

编程入门 行业动态 更新时间:2024-10-11 23:17:28
本文介绍了检测到“我正在跑步"在 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线程关联).如果您不使用 QObject::moveToThread 更改它,则它是创建对象的线程.

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 线程(qApp->thread()),但是如果您的对象发布到 this 的线程可能不起作用不存在于主 GUI 线程中.然而,如果你在那里做 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:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581617.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   检测到   事件   Qt   quot

发布评论

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

>www.elefans.com

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