Slot is being called multiple times every time a signal is emitted

前端 未结 1 1237
暗喜
暗喜 2020-11-30 08:46

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

in a.cpp

{
 QObject::connect(m_ptheFlange2Details,SIGNAL(GetFlang1DimAfterAn         


        
相关标签:
1条回答
  • 2020-11-30 09:28

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

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

    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).

    0 讨论(0)
提交回复
热议问题