Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt Signals and Slot connected twice... what happens?

What happens if the same signal and slot is connected twice?

How is the mechanism handled?

like image 420
itapadar Avatar asked Aug 20 '10 11:08

itapadar


People also ask

Can you connect one Qt to multiple slots?

One signal can be connected to many slots: When the signal is emitted, the slots are called one after the other, in an unspecified order.

How do signals and slots work Qt?

In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal.

In what order will the slots be executed if they are connected to one signal?

According to Qt documentation: If several slots are connected to one signal, the slots will be executed one after the other, in the order they have been connected, when the signal is emitted.

Are Qt signals and slots thread safe?

It is generally unsafe to provide slots in your QThread subclass, unless you protect the member variables with a mutex. On the other hand, you can safely emit signals from your QThread::run() implementation, because signal emission is thread-safe.


2 Answers

A few weeks ago, we had an intern accidentally connect a signal to a slot more than once. The idea was that under one condition, you'd have the slot connected to the signal, and under another condition you'd disconnect it. When you changed modes, you'd do the appropriate work.

Well, he forgot to to disconnect when appropriate. So every time you changed modes, you had a new connection to the slot.

The end result? 1 connection == 1 call to slot. 2 connections == 2 calls to slot. 3 connections == 3 calls to slot, etc. These calls happened "simultaneously" (I know in actuality they did not since they are on the same event thread, but what I mean was all calls were processed in succession).

As @Job points out in one of his comments (he deserves credit, so please do not upvote me for his work), Qt::UniqueConnection will prevent this issue.

like image 72
San Jacinto Avatar answered Sep 20 '22 23:09

San Jacinto


Usually bad things. It's perfectly acceptable to connect the slot twice or even more times but when the signal gets fired your slot will be called for each connection you made which is probably not what you want.

Note that it is not necessarily wrong to have multiple connections. There are (probably) perfectly valid uses for it. They are quite rare, I certainly can't think of any time I've used it as a feature. All the situations I can recall where there was a multiple connection turned out to be a bug rather than intended.

like image 22
Troubadour Avatar answered Sep 17 '22 23:09

Troubadour