从非 Qt 线程或外部 Qt 主事件循环以 4.5 发出 Qt 信号 [英] emit Qt signal from non Qt Thread or ouside Qt main event loop with at 4.5

查看:40
本文介绍了从非 Qt 线程或外部 Qt 主事件循环以 4.5 发出 Qt 信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从非 Qt 线程调用 emit signal1().我所说的非 Qt 线程不是来自 GUI 事件循环,也不是来自任何 QThread run() 方法或任何 QThread 自己的事件循环.

I'm calling a emit signal1() from a non Qt thread. By non Qt thread I mean not from the GUI Event Loop and not from any QThread run() method or any QThread own event loop.

它只是一个调用 QObject 方法的 pthread (pthread_create()),它发出信号.

It is simply a pthread (pthread_create()) that calls a method of a QObject which emits signals.

例如:

MyQbject: public QObject
{
...
void emitBunchOfSignals()
{
 emit signal1();
 emit signal2();
 ...
}
...
}

我的 pthread 的run"方法有一个指向 MyObject 实例的指针(在主 Qt GUI 线程上下文中创建的实例,而不是 pthread)调用 emitBunchOfSignals() 方法.

the "run" method of my pthread which has a pointer to a MyObject instance (instance that was created within the main Qt GUI thread context NOT the pthread) calls the emitBunchOfSignals() methods.

在 Qt 4.5 之前,这很糟糕.现在,Qt 4.5 会处理这个吗?它是否调用 qApp->PostEvent() 或其他东西,以便在 Qt GUI 线程(以及插槽)内发出信号?

Before Qt 4.5 that was nasty. Now, does Qt 4.5 handle this ? Does it call qApp->PostEvent() or something so the signal is emitted within the Qt GUI Thread (and thus the slot as well) ?

谢谢

推荐答案

您需要确保使用到来自线程的排队连接,因为 Qt 无法自动感知哪个对象属于哪个线程(线程亲和性"是文档中使用的术语).您在连接时执行此操作:

What you need to make sure is that you use a queued connection to a from threads, as Qt cannot autmatically sense which object that belong to which thread ("thread affinity" is the term used in the documentation). You do this when connecting:

connect(src, SIGNAL(signal-signature), dest, SLOT(slot-signature), Qt::QueuedConnection);

这将导致信号被放置在目标的事件循环上,并在其线程运行时调用插槽(即其事件循环).

That will result in the signal being put on the event loop of the destination, and the slot being called when its thread is running (i.e. its event loop).

这篇关于从非 Qt 线程或外部 Qt 主事件循环以 4.5 发出 Qt 信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆