Why do I need to decorate connected slots with pyqtSlot?
Asked Answered
M

2

30

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?
Mancy answered 30/10, 2016 at 4:7 Comment(0)
H
33

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:

Heerlen answered 30/10, 2016 at 16:1 Comment(3)
Also, (at least in PySide; though, I think it's true of PyQt as well), you must use the slot decorator if you want to send signal data across threads.Diode
@BrendanAbel. It's not required for cross-thread signals in either PySide or PyQt. The only exception to this is if a signal is connected before moving an object to another thread - but that only affects PyQt. This is the scenario I mentioned in my answer above (see this other answer for a more complete explanation).Heerlen
Thanks a lot for this!! took me ages to figure out why populating a sub-menu of a QMenu from a different tread didn't trigger the connected methods... @pyqtSlot finally did the trickRebirth
F
8

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.

Fincher answered 24/4, 2018 at 15:5 Comment(2)
+1 for pointing that out, but sad to see you are more constrained by the editor than by the interpreter... strange design choice.Washboard
This is significantly important when you're developing designer plugins, and features not exposing may not be easily aware by the user.Fincher

© 2022 - 2024 — McMap. All rights reserved.