What are signals and slots?


Can someone explain in simple terms the "signals and slots" pattern?

2/10/2015 8:56:49 PM

Accepted Answer

Signals and slots are a way of decoupling a sender (the signal) and zero or more receivers (the slots). Let's say you a system which has events that you want to make available to any other part of the system interested in those events. Rather than hard-wiring the code that generates event to the code that wants to know about those events, you would use a signals and slots pattern.

When the sender signals an event (usually by calling the function associated with that event/signal) all the receivers for that event are automatically called. This allows you to connect and disconnect receivers as necessary during the lifetime of the program.

Since this question was tagged C++, here is a link to the Boost.Signals library which has a much more thorough explanation.

11/23/2008 8:25:00 PM

I think one can describe signals and slots best when you are looking at them as a possible implementation vehicle for the Observer Pattern or Publish/Subscriber Pattern. There is one signal, for example buttonPressed(IdType) on the Publisher Side. Whenever the button is pressed, all slots that are connected to that signal are called. Slots are on the Subscriber Side. A slot could for example be sendMail(IdType) .

Along with the event "button pressed", the slot would know which button was pressed, since the id would have been handed over. IdType represents the type of the data sent over the connection between the Publisher and the Subscriber. An operation possible for the Subscriber would be connect(signal, slot) which could connect buttonPressed(IdType) with sendMail(IdType), so that if the button is pressed, that particular slot is called.

The good thing about this is that the subscriber (the slot side) doesn't need to care about details of the signal. It just needs to connect. Thus, here we have a great deal of loose coupling. You can change the buttons implementation, but the interface for the slots would still be the same.

Look at Qt Signals/Slots or Boost Signals for more informations.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow