PDA

View Full Version : sending signals between two different instances of two different classes?



dsab123
14th June 2012, 21:03
I love the way signals and slots works compared to callback functions, but I'm having a problem that I might have solved in an awkward way.
I have two classes, class A and B. I create an instance of each, and then somewhere in class A, I have to emit a signal to a slot in class B.

But how do I get that instance of B at runtime?


What I did (which is the awkward part):



A foo;
B bar;

QObject::connect(&foo, SIGNAL(someSignal()), &bar, SLOT(someSlot()));


I've used signals and slots once before (about a week ago), so I know how they work (I think), but there is some other way to do this, I hope..is there?

Thanks!

ChrisW67
15th June 2012, 00:23
But how do I get that instance of B at runtime/
Like you have or by keeping pointers to the objects. Once connected they stay connected.

I am not sure what you are expecting.

dsab123
15th June 2012, 12:33
so then it's not bad practice to have connections in main()? If not, then I guess my problem is solved.
Thanks ChrisW67!

wysota
15th June 2012, 12:37
so then it's not bad practice to have connections in main()?
Quite the opposite. It's best to have connect statements between objects A and B outside of their definitions. This provides so called "loose coupling" of objects.

ChrisW67
15th June 2012, 23:30
so then it's not bad practice to have connections in main()? If not, then I guess my problem is solved.
There's nothing in my response and nothing in your question regarding main() or where you should/should not connect objects.

As Wysota says, you generally connect objects from somewhere outside the objects. If main() is the logical place to do that then do it there.