我具有此功能来更新一些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事件线程中
发布评论