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

被折叠的 条评论
为什么被折叠?



