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?
If I understand you correctly you may want to do something like this?
A * a;
QList<A *> aList;
int aCounter = 0;
while(aCounter < 2)
{
a = new A;
aList.push_back(a);
if ( aCounter == 0 )
connect(this,SIGNAL(somethingHappened()),aList[aCounter],SLOT(doSometing()));
aCounter++;
}
This connects the signal only to the first object (but that's quite obvious). It is not possible to connect a signal to multiple slots, but send it out to just one.
If this is really your intention it would be more elegant if you actually connected this one outside the loop.
Another possibility would be to connect everything like you did before, but store some kind ob member variable in each instance of A and make the behavior of doSomething() dependant on that.