c++ - Qt signals and slots in different classes -
i have class x slot, , class y signal. i'm setting connection class x, , created public method in class y emit signal class x (i'm not sure step necessary).
then, if call method class x, signal emitted, , slot executed. if emit signal class y, slot never executed , don't understand why.
may stablish connection @ class y?
this pseudo-code tries explain want:
class x : public qwidget { q_object x(){ connect(y::getinstance(), signal(updatesignal(int)), this, slot(updatestatus(int))); y::getinstance().emitsignal(somevalue); // works } public slots: void updatestatus(int value); } class y : public qobject { q_object y(){ } public: y getinstance(); void emitsignal(int value) { emit updatesignal(value); } signal: void updatesignal(int value); } class z : public y { z(){ } init(){ emitsignal(somevalue); // doesn't work } }
remember connections not between classes, between instances. if emit signal , expect connected slots called, must emitted on instance on connection made. that's problem.
assuming y singleton:
if connect( y::getinstance(), ... )
and y::getinstance() new y() @ point, constructor of y called before connection set up. that, signal emitted slot not listen yet.
apart that, best 1 of following things, though not emit signal in constructor of y these approaches:
- use third class z knows both x , y, , connection there
- dependency injection. means x gets instance of y in constructor:
example dependency injection constructor:
x::x( y* const otherclass ) { connect( otherclass, signal( ... ), this, slot( ... ) }
Comments
Post a Comment