简体   繁体   中英

Passing check state with QtPushButton.clicked signal

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.

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, ie, to QML , and it is said to be slightly faster .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM