Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to decorate connected slots with pyqtSlot?

Tags:

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:

  1. What am I losing by doing it this way?
  2. What is the reason pyqtSlot is required?
like image 798
NirIzr Avatar asked Oct 30 '16 04:10

NirIzr


People also ask

What is pyqtSlot decorator?

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++.

What is a PYQT slot?

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.


2 Answers

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:

  • PyQt5 signal/slot connection performance
like image 171
ekhumoro Avatar answered Dec 11 '22 11:12

ekhumoro


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.

like image 40
Tong Avatar answered Dec 11 '22 11:12

Tong