views:

109

answers:

2

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?

+1  A: 

As far as I understand your question you want to know if doSomething() is being called on the first or the second object. The way I would probably do that is to give class A a boolean member first and set it inside your loop. This way the object knows its position. If you have more objects, you could just give them a counter. To keep track, have a static counter variable on class A. All depends on what you are really trying to achieve here.

It is perfectly sound to connect signals in loops.

A * a;
QList<A *> aList;
int aCounter = 0;

while( aCounter < 2 )
{
   aList.push_back( new A );
   ++aCounter;
}

connect( this, SIGNAL( somethingHappened() ), aList[0], SLOT( doSometing() ) );
ufotds
My purpose is to do something with first A object not second one. Is unique variable only way to achieve this?
onurozcelik
In that case, only connect the first one. ;-)Pull the connect call outside (after) the loop. Pass aList[0] to connect() as third parameter.
ufotds
+1  A: 

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.

gre
Ok. I am doing same thing with id variable. This question make me to understand signal-slot architecture better. I accept it.
onurozcelik
for more elegance I would propose to put the connect call after the while, and omit the condition..., just use aList[0]
ufotds
Yes. That's what I meant with "If this is really your intention it would be more elegant if you actually connected this one outside the loop." Sorry, I should have made it clearer.
gre