Passing check state with QtPushButton.clicked signal

265 Views Asked by At

I'm working on a project and trying to pass the checked state of a checkable button to a function via button.clicked.connect(self.button_checked) and ran across an issue. If I use the "decoration" @QtCore.pyqtSlot() before my callable then the checked state will not pass. But if I remove the decoration the function works as expected and written in documentation. See code below for the two cases:

With decoration

...
btn = QPushButton("Push")
btn.setCheckable(True)
btn.toggled.connect(self.button_checked)
...
@QtCore.pyqtSlot()
def button_checked(self, checked):
    print("checked", checked)
...

I get the error TypeError: button_checked() missing 1 required positional argument: 'checked' when the button is pushed. But when I remove QtCore.pyqtSlot() and just have:

...
btn = QPushButton("Push")
btn.setCheckable(True)
btn.toggled.connect(self.button_checked)
...
def button_checked(self, checked):
    print("checked", checked)
...

The button works as expected and prints checked True or checked False depending on the checked state.

What is the @QtCore.pyqtSlot() for? I am still new to QtPy and don't have a great grasp on this lines purpose. Do I need to explicitly assign a slot in this case? I've found that it can be necessary in some specific situations (function of pyqtSlot) and is considered good practice, but it seems to have an effect I don't want in this case.

1

There are 1 best solutions below

1
On

I get the error TypeError: button_checked() missing 1 required positional argument: 'checked'

That's because your slot doesn't take any arguments. Change @QtCore.pyqtSlot() to @QtCore.pyqtSlot(bool)

My question is what is the @QtCore.pyqtSlot() for?

It is used by the QMetaObjectSystem that is required by C++ Qt to do runtime dynamic stuff, like calling slots with the right signature. Read more here. In the Python case it is not needed due to the dynamic nature of Python.

Nevertheless it is required if you want to expose your slots away from Python, i.e., to QML, and it is said to be slightly faster.