每次发射信号时,都会多次调用插槽 [英] Slot is being called multiple times every time a signal is emitted

查看:132
本文介绍了每次发射信号时,都会多次调用插槽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个块中使用一个信号和插槽连接。我的代码如下

I am using one signal and slot connection in a block. My code as follows

in a.cpp

{
 QObject::connect(m_ptheFlange2Details,SIGNAL(GetFlang1DimAfterAnalysis()),
                 this,SLOT(GetFlang1DimAftrAnalysis()));

 m_ptheFlange2Details->get();// one function inside which i am emiting
                             // GetFlang1DimAfterAnalysis() signal ;

 QObject::disconnect(m_ptheFlange2Details,SIGNAL(GetFlang1DimAfterAnalysis()),
                     this,SLOT(GetFlang1DimAftrAnalysis()));

}

该插槽被称为很多次。

Inside the get() function when this emit statement executes, the slot is called lots of times. Where as according to me it should call only once.

推荐答案

如一些注释所述,这通常是由调用连接更多一次。每次连接时,该插槽将被调用一次。例如,当 signal()发出一次时,以下代码将导致 slot()被调用3次。

As stated in some of the comments, this is usually caused by calling the connect more the once. The slot will be called once for every time the connection is made. For example, the following code will result in slot() being called 3 times when signal() is emitted once.

connect(obj, SIGNAL(signal()), obj2, SLOT(slot()));
connect(obj, SIGNAL(signal()), obj2, SLOT(slot()));
connect(obj, SIGNAL(signal()), obj2, SLOT(slot()));

如果您在可能运行多次的代码中进行连接,通常是一个好主意使用 Qt :: UniqueConnection 作为第5个参数。下面的代码将导致 slot()被调用1次,当 signal() >

If you are doing connects in code that may be run more than once, it is generally a good idea to use Qt::UniqueConnection as the 5th parameter. The following code will result in slot() being called 1 time when signal() is emitted once.

connect(obj, SIGNAL(signal()), obj2, SLOT(slot()), Qt::UniqueConnection);
connect(obj, SIGNAL(signal()), obj2, SLOT(slot()), Qt::UniqueConnection);
connect(obj, SIGNAL(signal()), obj2, SLOT(slot()), Qt::UniqueConnection);

我猜你的代码不能正常工作的原因是因为你省略第5个参数, connect默认为 Qt :: DirectConnection (对于单线程程序)。这会立即调用槽,就像它是一个函数调用。这意味着可以在断开连接之前再次调用连接(如果程序中有循环)。

I'm guessing the reason your code is not working correctly is because you are omitting the 5th parameter and connect defaults to Qt::DirectConnection (for single threaded programs). This immediately calls the slot as if it were a function call. This means that it is possible for connect to be called again before the disconnect happens (if there are loops in your program).

这篇关于每次发射信号时,都会多次调用插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆