PDA

View Full Version : Signal - Slot connection inside loop



onurozcelik
24th June 2010, 12:15
In my code I am creating new objects of same type inside loop and connecting a signal to object slot. Here is my trial.


A * a;
QList<A *> aList;
int aCounter = 0;
while(aCounter < 2)
{
a = new A;
aList.push_back(a);
connect(this,SIGNAL(somethingHappened()),aList[aCounter],SLOT(doSometing()));
aCounter++;

}

When somethingHappened signal is emitted. Both objects slot is called. But I need to handle them seperately. Is it wrong to connect signal to a slot inside loop? If not how can I achieve my desire?

squidge
24th June 2010, 12:59
You are connecting the signal to both objects, so yes, both objects will be called when you emit that signal.

If you want to handle them seperately, you would need different signal for each object.

Or just call the method in the object directly.

area51
24th June 2010, 13:18
Hi, take a look at QSignalMapper, maybe that's what you're looking for?

See http://doc.trolltech.com/4.6/qsignalmapper.html

Good luck!

high_flyer
24th June 2010, 13:26
in addition to the post above me, you can ask sender() in the slot.

squidge
24th June 2010, 16:33
How the code is written, the sender() will be the same in each case, so I don't see how that would work? Only the recipient changes.

high_flyer
24th June 2010, 16:45
Then I fail to understand the problem to begin with.
If you have one sender, which you connected to many objects with one signal, then all the objects will react to that signal.
What is the behavior you are after?