槽函数获取sender_Qt 使用 lambda 表达式做为槽函数时为什么使用 QObject::sender() 获取到的发送信号对象指针为空?...

本文探讨了在使用 lambda 表达式作为槽函数时,为何调用 QObject::sender() 函数可能返回空指针。由于 lambda 表达式隐含使用 Qt::DirectConnection 连接,若信号和槽在同一线程,sender() 可能返回无效指针。了解这一行为的原因和限制对于理解 Qt 的信号与槽机制至关重要。

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

/*!

Returns a pointer to the object that sent the signal, if called in

a slot activated by a signal; otherwise it returns 0. The pointer

is valid only during the execution of the slot that calls this

function from this object's thread context.

The pointer returned by this function becomes invalid if the

sender is destroyed, or if the slot is disconnected from the

sender's signal.

\warning This function violates the object-oriented principle of

modularity. However, getting access to the sender might be useful

when many signals are connected to a single slot.

\warning As mentioned above, the return value of this function is

not valid when the slot is called via a Qt::DirectConnection from

a thread different from this object's thread. Do not use this

function in this type of scenario.

\sa senderSignalIndex(), QSignalMapper

*/

QObject *QObject::sender() const

{

Q_D(const QObject);

QMutexLocker locker(signalSlotLock(this));

if (!d->currentSender)

return 0;

for (QObjectPrivate::Connection *c = d->senders; c; c = c->next) {

if (c->sender == d->currentSender->sender)

return d->currentSender->sender;

}

return 0;

}

使用 lambda 表达式做槽函数时,相当于使用了 Qt::DirectConnection 方式连接槽,都在同一个线程中,故获取发送信号对象指针时,直接给你返回了 0.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值