Qt Signal Slot Template Class

Posted By admin On 09/04/22
Qt Signal Slot Template Class Average ratng: 3,6/5 3959 reviews
  1. Qt Signal Slot Template Classes
  2. Qt Signal Slot Template Classification
  3. Qt Signal Slot Template Classic
  4. Qt Signal Slot Template Classifieds
Slot
  • Old syntax Qt 5 continues to support the old string-based syntax for connecting signals and slots defined in a QObject or any class that inherits from QObject (including QWidget) connect (sender, SIGNAL (valueChanged (QString, QString)), receiver, SLOT (updateValue (QString))); New: connecting to QObject member.
  • Signals and slots are loosely coupled: A class which emits a signal neither knows nor cares which slots receive the signal. Qt's signals and slots mechanism ensures that if you connect a signal to a slot, the slot will be called with the signal's parameters at the right time. Signals and slots can take any number of arguments of any type.

I’ve been asked multiple times how I would implement a signal / slot mechanism in modern C++. Here is the answer!

What’s the Signal / Slot Pattern?

[...] a language construct [...] which makes it easy to implement the Observer pattern while avoiding boilerplate code. The concept is that GUI widgets can send signals containing event information which can be received by other controls using special functions known as slots. - Wikipedia

The receivers of signals are called Slots in Qt terminology. A number of standard slots are provided on Qt classes to allow you to wire together different parts of your application. However, you can also use any Python function as a slot, and therefore receive the message yourself. A QObject only holds data and logic you can use in QML as properties, signals and slots. When registering a QObject class as a type for QML, keep this restriction in mind. To create a QML Item with C which should support a visual representation with all default properties, derive from QQuickItem instead.

So basically it allows for event based inter-object communication. In my opinion it’s intuitive to use and produces easily readable code when used in a moderate amount. And the big plus: It can be added to your program with one simple template class!

There are many libraries around (refer to the linked Wikipedia article) implementing this pattern, but it’s so easy to implement on you own that I would recommend to do this without an additional dependency. All you need is the header I posted below. And it’s a good exercise.

The signal template class

Below you can find the entire class. Because this class is using variadic templates you can define signals which pass any kind of data to their slots. Basically you can create signals which allow for arbitrary slot signatures. The emit method will accept the same argument types you declared as template parameters for the Signal class. The class is documented with comments and should be quite understandable. Further below you will find two usage examples.

Simple usage

The example below creates a simple signal. To this signal functions may be connected which accept a string and an integer. A lambda is connected and gets called when the emit method of the signal is called.

When you saved the Signal class as Signal.hpp and the above example as main.cpp you can compile the example with:

And if you execute the resulting application you will get the following output:

Advanced usage

This example shows the usage with classes. A message gets displayed when the button is clicked. Note that neither the button knows anything of a message nor does the message know anything about a button. That’s awesome! You can compile this example in the same way as the first.

You may also connect member functions which take arguments (Thank you FlashingChris for pointing out how to do this without std::placeholders!). In the following example Alice and Bob may say something and the other will hear it:

Issues & next steps

There are two drawbacks in this simple implementation: It’s not threadsafe and you cannot disconnect a slot from a signal from within the slot callback. Both problems are easy to solve but would make this example more complex.

Using this Signal class other patterns can be implemented easily. In a follow-up post I’ll present another simple class: the Property. This will allow for a clean implementation of the observer pattern.

Have some fun coding events in C++!

Edit on 2020-10-19:

  • Add move-copy-constructor and move-assignment-operator
  • Add emit_for_all_but_one and emit_for methods.
  • Remove previously added std::forward.
Please enable JavaScript to view the comments powered by Disqus.blog comments powered by ClassificationDisqus

Manage connections between VTK events and Qt slots. More...

#include <vtkEventQtSlotConnect.h>

[legend]
Collaboration diagram for vtkEventQtSlotConnect:
Qt signal slot template classifieds
[legend]

Public Types

typedef vtkObjectSuperclass

Public Member Functions

virtual vtkTypeBoolIsA (const char *type)
Return 1 if this class is the same type of (or a subclass of) the named class. More...
vtkEventQtSlotConnect * NewInstance () const
void PrintSelf (ostream &os, vtkIndent indent) override
Print the current connections between VTK and Qt. More...
virtual void Connect (vtkObject *vtk_obj, unsigned long event, const QObject *qt_obj, const char *slot, void *client_data=nullptr, float priority=0.0, Qt::ConnectionType type=Qt::AutoConnection)
Connect a vtk object's event with a Qt object's slot. More...
virtual void Disconnect (vtkObject *vtk_obj=nullptr, unsigned long event=vtkCommand::NoEvent, const QObject *qt_obj=nullptr, const char *slot=nullptr, void *client_data=nullptr)
Disconnect a vtk object from a qt object. More...
virtual int GetNumberOfConnections () const
Allow to query vtkEventQtSlotConnect to know if some Connect() have been setup and how many. More...
Public Member Functions inherited from vtkObject
vtkBaseTypeMacro (vtkObject, vtkObjectBase)
virtual void DebugOn ()
Turn debugging output on. More...
virtual void DebugOff ()
Turn debugging output off. More...
bool GetDebug ()
Get the value of the debug flag. More...
void SetDebug (bool debugFlag)
Set the value of the debug flag. More...
virtual void Modified ()
Update the modification time for this object. More...
virtual vtkMTimeTypeGetMTime ()
Return this object's modified time. More...
unsigned long AddObserver (unsigned long event, vtkCommand *, float priority=0.0f)
Allow people to add/remove/invoke observers (callbacks) to any VTK object. More...
unsigned long AddObserver (const char *event, vtkCommand *, float priority=0.0f)
vtkCommand * GetCommand (unsigned long tag)
void RemoveObserver (vtkCommand *)
void RemoveObservers (unsigned long event, vtkCommand *)
void RemoveObservers (const char *event, vtkCommand *)
vtkTypeBoolHasObserver (unsigned long event, vtkCommand *)
vtkTypeBoolHasObserver (const char *event, vtkCommand *)
void RemoveObserver (unsigned long tag)
void RemoveObservers (unsigned long event)
void RemoveObservers (const char *event)
void RemoveAllObservers ()
vtkTypeBoolHasObserver (unsigned long event)
vtkTypeBoolHasObserver (const char *event)
template<class U , class T >
unsigned long AddObserver (unsigned long event, U observer, void(T::*callback)(), float priority=0.0f)
Overloads to AddObserver that allow developers to add class member functions as callbacks for events. More...
template<class U , class T >
unsigned long AddObserver (unsigned long event, U observer, void(T::*callback)(vtkObject *, unsigned long, void *), float priority=0.0f)
template<class U , class T >
unsigned long AddObserver (unsigned long event, U observer, bool(T::*callback)(vtkObject *, unsigned long, void *), float priority=0.0f)
Allow user to set the AbortFlagOn() with the return value of the callback method. More...
int InvokeEvent (unsigned long event, void *callData)
This method invokes an event and return whether the event was aborted or not. More...
int InvokeEvent (const char *event, void *callData)
int InvokeEvent (unsigned long event)
int InvokeEvent (const char *event)
Public Member Functions inherited from vtkObjectBase
const char * GetClassName () const
Return the class name as a string. More...
virtual vtkIdTypeGetNumberOfGenerationsFromBase (const char *name)
Given the name of a base class of this class type, return the distance of inheritance between this class type and the named class (how many generations of inheritance are there between this class and the named class). More...
virtual void Delete ()
Delete a VTK object. More...
virtual void FastDelete ()
Delete a reference to this object. More...
void InitializeObjectBase ()
void Print (ostream &os)
Print an object to an ostream. More...
virtual void PrintHeader (ostream &os, vtkIndent indent)
virtual void PrintTrailer (ostream &os, vtkIndent indent)
virtual void Register (vtkObjectBase *o)
Increase the reference count (mark as used by another object). More...
virtual void UnRegister (vtkObjectBase *o)
Decrease the reference count (release by another object). More...
int GetReferenceCount ()
Return the current reference count of this object. More...
void SetReferenceCount (int)
Sets the reference count. More...
bool GetIsInMemkind () const
A local state flag that remembers whether this object lives in the normal or extended memory space. More...

Static Public Member Functions

static vtkEventQtSlotConnect * New ()
static vtkTypeBoolIsTypeOf (const char *type)
static vtkEventQtSlotConnect * SafeDownCast (vtkObjectBase *o)
Static Public Member Functions inherited from vtkObject
static vtkObject * New ()
Create an object with Debug turned off, modified time initialized to zero, and reference counting on. More...
static void BreakOnError ()
This method is called when vtkErrorMacro executes. More...
static void SetGlobalWarningDisplay (int val)
This is a global flag that controls whether any debug, warning or error messages are displayed. More...
static void GlobalWarningDisplayOn ()
static void GlobalWarningDisplayOff ()
static int GetGlobalWarningDisplay ()
Static Public Member Functions inherited from vtkObjectBase
static vtkTypeBoolIsTypeOf (const char *name)
Return 1 if this class type is the same type of (or a subclass of) the named class. More...
static vtkIdTypeGetNumberOfGenerationsFromBaseType (const char *name)
Given a the name of a base class of this class type, return the distance of inheritance between this class type and the named class (how many generations of inheritance are there between this class and the named class). More...
static vtkObjectBase * New ()
Create an object with Debug turned off, modified time initialized to zero, and reference counting on. More...
static void SetMemkindDirectory (const char *directoryname)
The name of a directory, ideally mounted -o dax, to memory map an extended memory space within. More...
static bool GetUsingMemkind ()
A global state flag that controls whether vtkObjects are constructed in the usual way (the default) or within the extended memory space. More...

Protected Member Functions

virtual vtkObjectBase * NewInstanceInternal () const
void RemoveConnection (vtkQtConnection *)
vtkEventQtSlotConnect ()
~vtkEventQtSlotConnect () override
Protected Member Functions inherited from vtkObject
vtkObject ()
~vtkObject () override
void RegisterInternal (vtkObjectBase *, vtkTypeBool check) override
void UnRegisterInternal (vtkObjectBase *, vtkTypeBool check) override
void InternalGrabFocus (vtkCommand *mouseEvents, vtkCommand *keypressEvents=nullptr)
These methods allow a command to exclusively grab all events. More...
void InternalReleaseFocus ()
Protected Member Functions inherited from vtkObjectBase
vtkObjectBase ()
virtual ~vtkObjectBase ()
virtual void ReportReferences (vtkGarbageCollector *)
vtkObjectBase (const vtkObjectBase &)
void operator= (const vtkObjectBase &)

Protected Attributes

vtkQtConnections * Connections
Protected Attributes inherited from vtkObject
bool Debug
vtkTimeStampMTime
vtkSubjectHelper * SubjectHelper
Protected Attributes inherited from vtkObjectBase
std::atomic< int32_t > ReferenceCount
vtkWeakPointerBase ** WeakPointers

Friends

class vtkQtConnection

Additional Inherited Members

Static Protected Member Functions inherited from vtkObjectBase
static vtkMallocingFunctionGetCurrentMallocFunction ()
static vtkReallocingFunctionGetCurrentReallocFunction ()
static vtkFreeingFunctionGetCurrentFreeFunction ()
static vtkFreeingFunctionGetAlternateFreeFunction ()

Detailed Description

Manage connections between VTK events and Qt slots.

vtkEventQtSlotConnect provides a way to manage connections between VTK events and Qt slots. Qt slots to connect with must have one of the following signatures:

  • MySlot()
  • MySlot(vtkObject* caller)
  • MySlot(vtkObject* caller, unsigned long vtk_event)
  • MySlot(vtkObject* caller, unsigned long vtk_event, void* client_data)
  • MySlot(vtkObject* caller, unsigned long vtk_event, void* client_data, void* call_data)
  • MySlot(vtkObject* caller, unsigned long vtk_event, void* client_data, void* call_data, vtkCommand*)

Definition at line 57 of file vtkEventQtSlotConnect.h.

Member Typedef Documentation

Superclass

typedef vtkObjectvtkEventQtSlotConnect::Superclass

Definition at line 61 of file vtkEventQtSlotConnect.h.

Constructor & Destructor Documentation

vtkEventQtSlotConnect()

vtkEventQtSlotConnect::vtkEventQtSlotConnect ()
protected

~vtkEventQtSlotConnect()

vtkEventQtSlotConnect::~vtkEventQtSlotConnect ()
overrideprotected

Member Function Documentation

New()

Qt signal slot template classification
static vtkEventQtSlotConnect* vtkEventQtSlotConnect::New ()
static

IsTypeOf()

static vtkTypeBool vtkEventQtSlotConnect::IsTypeOf (const char * type)
static

IsA()

virtual vtkTypeBool vtkEventQtSlotConnect::IsA (const char * name)
virtual

Return 1 if this class is the same type of (or a subclass of) the named class.

Returns 0 otherwise. This method works in combination with vtkTypeMacro found in vtkSetGet.h.

Reimplemented from vtkObjectBase.

SafeDownCast()

static vtkEventQtSlotConnect* vtkEventQtSlotConnect::SafeDownCast (vtkObjectBase * o)
static

NewInstanceInternal()

virtual vtkObjectBase* vtkEventQtSlotConnect::NewInstanceInternal () const
protectedvirtual

NewInstance()

vtkEventQtSlotConnect* vtkEventQtSlotConnect::NewInstance () const

PrintSelf()

void vtkEventQtSlotConnect::PrintSelf (ostream & os,
vtkIndentindent
)
overridevirtual

Print the current connections between VTK and Qt.

Reimplemented from vtkObject.

Connect()

virtual void vtkEventQtSlotConnect::Connect (vtkObject * vtk_obj,
unsigned long event,
const QObject * qt_obj,
const char * slot,
void * client_data = nullptr,
float priority = 0.0,
Qt::ConnectionType type = Qt::AutoConnection
)
virtual

Connect a vtk object's event with a Qt object's slot.

Qt Signal Slot Template Classes

Multiple connections which are identical are treated as separate connections.

Disconnect()

virtual void vtkEventQtSlotConnect::Disconnect (vtkObject * vtk_obj = nullptr,
unsigned long event = vtkCommand::NoEvent,
const QObject * qt_obj = nullptr,
const char * slot = nullptr,
void * client_data = nullptr
)
virtual

Disconnect a vtk object from a qt object.

Passing no arguments will disconnect all slots maintained by this object. Passing in only a vtk object will disconnect all slots from it. Passing only a vtk object and event, will disconnect all slots matching the vtk object and event. Passing all information in will match all information.

GetNumberOfConnections()

virtual int vtkEventQtSlotConnect::GetNumberOfConnections () const
virtual

Allow to query vtkEventQtSlotConnect to know if some Connect() have been setup and how many.

RemoveConnection()

void vtkEventQtSlotConnect::RemoveConnection (vtkQtConnection * )
protected

Friends And Related Function Documentation

vtkQtConnection

Qt signal slot template classes

Definition at line 95 of file vtkEventQtSlotConnect.h.

Member Data Documentation

Connections

Qt Signal Slot Template Classification

vtkQtConnections* vtkEventQtSlotConnect::Connections
protected

Definition at line 94 of file vtkEventQtSlotConnect.h.

Qt Signal Slot Template Classic

The documentation for this class was generated from the following file:

Qt Signal Slot Template Classifieds

  • GUISupport/Qt/vtkEventQtSlotConnect.h