簡體   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