Qt Signal Slot Observer Pattern

Qt connect class slots to designer signals

Signal/Slot is a widely used pattern, many frameworks have it built-in including Django, Qt and probably many others. If you have a standalone project then you probably don’t want to add a big dependency like PyQt or Django just for a Signal/Slot framework.

Qt Signals And Slots Tutorial

12 Sep 2004
Qt Signal Slot Observer Pattern
The article describes an efficient way to implement delegates in C++ using Signal and Slot pattern.

Introduction

In my previous article “Generic Observer Pattern and Events in C++”, we discussed classical “Observer Pattern” and its implementation in C++ using templates. An event class CppEvent introduced in that article allowed us to bind together loosely coupled classes, by connecting one class containing CppEvent to other class member functions. Member functions could be of any number and types of arguments, and no relations or special inheritance for model and view classes are required.

The only problem here is that we can’t delete our view without detaching it from the model first without risk of crashing our application on the next call of the event notification. It’s becoming annoying when we have many models created and deleted dynamically. To resolve this problem, we need a delegate which removes itself from the model when the view is deleted. To accomplish this task, we use Signal and Slot concept. This concept had been introduced in Trolltech Qt library and Boost C++ library.

Qt Signal Slot With 2 Arguments

Using Signal and Slots

To demonstrate how signals and slots work, we create a model class containing CppSignal member and a view class containing CppSlot.

Note that we use CppSignal1 to specify signal with one parameter; for two and three parameters there are CppSignal2 and CppSignal3. We could avoid this name multiplicity for standard C++ compiler, it’s done for portability with VC++ 6, which is still in use.

Qt Signal Slots

Note that slot member is initialized in the constructor of the view class. It’s initialized with pointer to the view class and member function. Now, to connect model to the view, we need to connect its signals with slots.

Now we can create another view and connect it to the same model.

Signal

In order to track return values from view's callback functions, we can use collector function object. For example, an object counting return values will be:

And when it is passed as a second parameter of emit_sig method, it will return sum of view responses.

Qt Signal Slot Parameter

Now we can delete one of the views and the sum of responses will change accordingly.

Signals and Slots implementation

Qt Signal Slot Connect

Implementation of CppSignal and CppSlot is very similar to CppEvent in “Generic Observer Pattern and Events in C++”.

Qt Signal Slot Thread