Warm tip: This article is reproduced from stackoverflow.com, please click
pyqt pyqt5 python signals-slots slot

PYQT5

发布于 2020-03-28 23:16:57

I am working on an PYQT5 interface, with a QPushButton supposed to call a slot function, which has default arguments.

self.button = QtWidgets.QPushButton("Button")
self.button.clicked.connect(self.doSomething)

def doSomething(self, boolVariable = True):
  print(boolVariable)

Result when I run doSomething function:

[in] object_instance.doSomething()
--> True

but if I click on the button, I get this result:

--> False

Can someone explain me why the default argument isn't taken into account ?

Thank you !

Questioner
Mat4444
Viewed
30
musicamante 2020-01-31 22:22

The clicked signal of QPushButton, like any class that inherits from QAbstractButton, has a checked argument which represents the current checked ("pressed") state of the button.

This signal is emitted when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button)

Push buttons emit the clicked signal when they are released; at that point, the button is not pressed and the signal argument will be False.

There are two possibilities to avoid that:

  1. connect the signal to a lambda:

    self.button.clicked.connect(lambda: self.doSomething())

  2. add a pyqtSlot decorator to the function, with no signature as argument:

    @QtCore.pyqtSlot()
    def doSomething(self, boolVariable = True):
        print(boolVariable)