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