Search code examples
pythonpyqtpyqt5signals-slotsslot

PYQT5 - Slot function does not take default argument


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 !


Solution

  • 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)