#python-decorators

tord_dellsen@diasp.eu

Python 3.9 has more flexible decorators which can be used with PyQt's signals+slots like this:

import sys
import logging
from PyQt5 import QtWidgets
from PyQt5 import QtCore

logging.basicConfig(level=logging.DEBUG)


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.button_qpb = QtWidgets.QPushButton("Button")
        self.setCentralWidget(self.button_qpb)
        self.show()

        @self.button_qpb.clicked.connect
        def on_button_clicked():
            print("clicked!")
            print(self.button_qpb.text())
            self.my_print()

    def my_print(self):
        print("my_print entered")


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    app.exec_()

Please note that the "slot function" on_button_clicked is an inner function. (Using an inner function seems to be the best approach)

Thank you to Geir Arne Hjelle at realpython.com who helped me with this!

#python #python-decorators #programming #pyqt