Qt signals and slots in different classes

本文讨论了在使用信号与槽机制时,连接操作的正确实现方式,特别关注于单例类的实例化时机。通过实例演示,展示了如何避免在构造函数中创建实例,从而确保信号在适当时刻被触发。

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

Remember that connections are not between classes, but between instances. If you emit a signal and expect connected slots to be called, it must be emitted on an instance on which the connection was made. That's your problem.

Assuming Y is a Singleton:

If you do connect( Y::getInstance(), ... )

and Y::getInstance() does new Y() at some point, then the constructor of Y is called before the connection is set up. Like that, the signal will be emitted but the slot will not listen to it yet.

Apart from that, it would be best to do one of the following things, though you could not emit the signal in the constructor of Y with these approaches:

  • Use a third class Z that knows both X and Y, and do the connection there
  • Dependency Injection. That means X gets an instance of Y in its constructor:

Example for a Dependency Injection Constructor:

X::X( Y* const otherClass )
{
    connect( otherClass, SIGNAL( ... ), this, SLOT( ... )
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值