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

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

问题描述

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

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

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

}

当这个emit 语句执行时,在get() 函数中,槽被调用了很多次.根据我的说法,它应该只调用一次.

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.

推荐答案

正如一些评论中所述,这通常是由于多次调用 connect 造成的.每次建立连接时都会调用一次插槽.例如,下面的代码将导致 slot()signal() 被发射一次时被调用 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()signal() 发出一次时被调用 1 次.

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 个参数并且连接默认为 Qt::DirectConnection(对于单线程程序).这会立即调用插槽,就好像它是一个函数调用一样.这意味着有可能在断开连接之前再次调用 connect(如果您的程序中存在循环).

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天全站免登陆