在Qt GUI事件线程中检测该"I'm running"

Detect that "I'm running" in Qt GUI event thread

本文关键字:running GUI Qt 事件 线程 检测      更新时间:2023-10-16

我有这个函数来更新一些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 线程!它是this所在的线程(请参阅 QObject 线程相关性)。如果不使用 QObject::moveToThread 更改它,则它是创建对象的线程。

这也是QCoreApplication::postEvent用来确定事件应该发布到哪个线程中的方法。目标线程必须运行QEventLoop来响应事件。

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