Image illustration python

Having learned QT in C++, now using it in python raised a few struggles. Today we talk about how to implement custom signals in your objects.

We will be building a simple toggling button that emit a custom ON/OFF signal when pressed.


In short :

Your object needs to inherit from QObject
Your signal is declared outside of your constructor

The Built

Our widget is going to inherit from QPushButton, and we are simply going to change the displayed text based on an internal state we will be toggling on every press. I will not enter in the details of building such an object (it could be the subject of an other article). Here is my implementation :

To this base we simply want to add a new signal. The first thing is to make sure your object inherit from QObject. In C++ you need the macro “Q_OBJECT” in your header file to be able to use the signals, here in python this is done through the inheritance with QObject. In our precise situation, we are inheriting from QPushButton which inherit from QWidget, himself inheriting from QObject. Which mean we are already fulfilling the first requirement.

The second thing to be careful about is to define your custom signals outside of your constructor. If not you will have an error message and a crash (so you will not miss it ;) ).

In our case that modifies the widget like that :

Hope this was helpful, if you are struggling with some implementation of PyQt and would like me to make a small article on that specific subject, leave your request in the comments ;) .

A full implementation of the button is available here.