Signals and slots is an approach used in some programming languages and libraries (for example, Boost and Qt ) that allows you to implement the "observer" pattern, minimizing the writing of duplicate code. The concept is that a component (often a widget) can send signals containing information about an event (for example: the text “word” was highlighted, the second tab was opened). In turn, other components can receive these signals through special functions - slots. A signal and slot system is well suited for describing a graphical user interface . Also, the signal / slot mechanism can be applied to asynchronous I / O (including sockets , pipe, devices with a serial interface, etc.) or event notifications. In the Qt library, thanks to the Meta-Object Compiler, there is no need to write a registration / deregistration / call code, since these sample parts of the code are generated automatically.
Alternative approaches
There are signal / slot system implementations based on C ++ templates . They have the advantage of not having to use the Meta-Object Compiler, as implemented in Qt .
Examples:
- libsigc ++ (Used in gtkmm , C ++ shell over Gtk + );
- sigslot ;
- Signals ;
- boost.signals2 ;
- Cpp :: Events ;
- Platinum ;
- JBroadcaster .
In the C # programming language, there is a similar construction with different terminology and syntax: events play the role of signals, and delegates play the role of slots. Another implementation of signals exists for ActionScript 3.0 , based on events from C # and signals / slots from Qt. Additionally, a local variable or a function pointer can be a delegate, while in Qt only a specially declared class method can be a slot. Due to the limitations of the language, there is no general implementation for ANSI C. But there is a limited option - c-sigslot .
Signals and slots in Qt ( C ++ )
You can create a signal in a class like this:
class A : public QObject
{
Q_OBJECT
public :
A ();
signals :
void someSignal ();
/ * ... * /
};
You can create a slot like this:
class B : public QObject
{
Q_OBJECT
public :
B ();
public slots :
void someSlot ();
/*...*/
};
To connect the signal and slot:
A classA ();
B classB ();
QObject :: connect ( & classA , SIGNAL ( someSignal ( int )), & classB , SLOT ( someSlot ( int )));
Links
- Signals and slots from Qt official documentation.
- Signals and slots from Boost documentation.
- William F. Humprey. Generalized Callbacks: C ++ and C # . Dr. Dobb's Journal (March, 01, 2003). The date of appeal is January 22, 2014.