I'm using pyqt5, and I have several methods connected using code similar to the following:
self.progress.canceled.connect(self.cancel)
Where, for example, self.cancel
is:
def cancel(self): self.timer.stop()
This code seems to work cleanly in multiple scenarios, without ever decorating cancel
with pyqtSlot
or doing anything special with it.
My questions are:
pyqtSlot
is required?The pyqtSlot() DecoratorDecorate a Python method to create a Qt slot. Parameters: types – the types that define the C++ signature of the slot. Each type may be a Python type object or a string that is the name of a C++ type. name – the name of the slot that will be seen by C++.
A slot is a Python callable. If a signal is connected to a slot then the slot is called when the signal is emitted. If a signal isn't connected then nothing happens. The code (or component) that emits the signal does not know or care if the signal is being used.
The main purpose of pyqtSlot
is to allow several different overloads of a slot to be defined, each with a different signature. It may also be needed sometimes when making cross-thread connections (see this answer for one such scenario). However, these use-cases are relatively rare, and in most PyQt applications it is not necessary to use pyqtSlot
at all. Signals can be connected to any python callable object, whether it is decorated as a slot or not.
The PyQt docs also state:
Connecting a signal to a decorated Python method also has the advantage of reducing the amount of memory used and is slightly faster.
However, in practice, this advantage is generally very small and will often be swamped by other factors. It has very little affect on raw signalling speed, and it would be necessary to make thousands of emits/connections before it started to have a significant impact on cpu load or memory usage. For an in depth analysis of these points, see this Code Project article by @Schollii:
Another advantage is when you design the custom widgets for Qt-designer, methods decorated by pyqtSlot
could be selected within Signal/Slot Editor
, otherwise you need to write the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With