Should I decorate slots in Pyside2 and if so how?

Heads up! You've already completed this tutorial.

RaSt | 2020-12-13 13:54:24 UTC | #1

Should I decorate slots in Pyside2 and if so how?

Example code of 2 different slots:

python
def createActions(self):

    buttonTriggered = QAction('Button Triggered', self)
    buttonTriggered.triggered.connect(self.onButtonTriggered)

    buttonToggled = QAction('Button Toggled', self)
    buttonToggled.setCheckable(True)
    buttonToggled.toggled.connect(lambda checked: self.onButtonToggled(checked))

def onButtonTriggered(self):
    pass

def onButtonToggled(self, checked):
    pass

Thanks


martin | 2020-12-18 00:34:01 UTC | #2

Hi RaSt welcome to the forum. You can decorate PySide2 slots the same way you do for PyQt5, just using the decorator

python
from PySide2.QtCore import Slot

@Slot
def slot
    pass

...rather than...

Over 10,000 developers have bought Create GUI Applications with Python & Qt!
Create GUI Applications with Python & Qt6
Take a look

Downloadable ebook (PDF, ePub) & Complete Source code

Also available from Payhip , Gumroad , Leanpub and Amazon Paperback

[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]

python
from PyQt5.QtCore import pyqtSlot

@pyqtSlot
def slot
    pass

...for PyQt5.

As to whether you should decorate the slots, it's a little trickier to answer -- but generally speaking no, you don't need to.

The only place I know the slot decorator is needed is when a) using threads, as it ensures the decorated method is started in the correct thread, or b) when you want to explicitly map a given slot to a specific call signature (types) in C++.

In your examples, the slots are running in the GUI thread and signal/slots are single-typed, so you don't need them.


RaSt | 2020-12-18 00:33:58 UTC | #3

hi martin, thanks for your answer. so I won't do it


Create GUI Applications with Python & Qt6 by Martin Fitzpatrick — (PyQt6 Edition) The hands-on guide to making apps with Python — Over 10,000 copies sold!

More info Get the book

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

Should I decorate slots in Pyside2 and if so how? was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt.