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

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

Leave a Comment