开发者

Signal - Slot connection inside loop

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(s开发者_如何学编程omethingHappened()),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.


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() ) );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜