Slot is being called multiple times every time a signal is emitted(每次发出信号时都会多次调用插槽)
问题描述
我在一个块中使用一个信号和插槽连接.我的代码如下
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).
这篇关于每次发出信号时都会多次调用插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:每次发出信号时都会多次调用插槽


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01