信号 - 环路内的槽连接
在我的代码中,我在循环内创建相同类型的新对象,并将信号连接到对象槽。这是我的审判。
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++;
}
当发生某事时发出信号。这两个对象的槽都被调用。但我需要单独处理它们。 将信号连接到循环内的插槽是否错误? 如果不能,我怎样才能实现我的愿望呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解正确的话,你可能想做这样的事情?
这仅将信号连接到第一个对象(但这很明显)。不可能将一个信号连接到多个插槽,但仅将其发送到一个插槽。
如果这确实是您的意图,那么如果您实际上将其连接到循环之外会更优雅。
另一种可能性是像以前一样连接所有内容,但在 A 的每个实例中存储某种 ob 成员变量,并使 doSomething() 的行为依赖于此。
If I understand you correctly you may want to do something like this?
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.
据我了解您的问题,您想知道是否在第一个或第二个对象上调用 doSomething() 。我可能会这样做的方法是首先给 A 类一个布尔成员并将其设置在循环中。这样物体就知道它的位置。如果你有更多的物体,你可以给它们一个计数器。为了跟踪,在 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.