繁体   English   中英

在Qt GUI事件线程中检测到“我正在运行”

[英]Detect that “I'm running” in Qt GUI event thread

我有这个功能来更新一些GUI的东西:

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

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

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的类似问题

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

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

请注意, 这可能不是主要的GUI-Thread 它是线程this住在(见QObject的线程关联) 如果不使用QObject::moveToThread更改它,则它是创建对象的线程。

这也是QCoreApplication::postEvent用于确定事件应发布到哪个线程的内容。 目标Thread必须运行QEventLoop才能响应该事件。

因此,检查main-GUI-Thread( qApp->thread() ),但如果您的对象不在主GUI-Thread中,则发布this线程可能不起作用。 但是,如果你在那里做GUI的东西,它应该存在于GUI-Thread中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM