QT中SIGNAL与SLOT连接的几种方式

QT的signal/slot连接方式包括Qt::DirectConnection、Qt::QueuedConnection、Qt::BlockingQueuedConnection和Qt::AutoConnection。Qt::DirectConnection在同一线程内立即执行,不适用于跨线程。Qt::QueuedConnection将信号包装为QEvent放入消息队列,可用于线程内或跨线程。Qt::BlockingQueuedConnection会阻塞直到槽执行,适合多线程间通信。Qt::AutoConnection则根据对象所在线程自动选择连接方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

signal/slot在底层会使用三种方式传递消息。参见QObject::connect()方法:

bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoCompatConnection )

最后一个参数是就是传递消息的方式了,有四个取值:


Qt::DirectConnection

When emitted, the signal is immediately delivered to the slot.

假设当前有4个slot连接到QPushButton::clicked(bool),当按钮被按下时,QT就把这4个slot按连接的时间顺序调用一遍。显然这种方式不能跨线程(传递消息)。



Qt::QueuedConnection

When emitted, the signal is queued until the event loop is able to deliver it to the slot.

假设当前有4个slot连接到QPushButton::clicked(bool),当按钮被按下时,QT就把这个signal包装成一个 QEvent,放到消息队列里。QApplication::exec()或者线程的

QThread::exec()会从消息队列里取消息,然后调用 signal关联的几个slot。这种方式既可以在线程内传递消息,也可以跨线程传递消息。



Qt::BlockingQueuedConnection

Same as QueuedConnection, except that the current thread blocks until the slot has been delivered. This connection type should

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值