0

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 !

Mat4444
  • 3
  • 1
  • Related: https://stackoverflow.com/questions/59970871/decorator-adds-an-unexpected-argument – Heike Jan 31 '20 at 10:56

1 Answers1

0

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)
musicamante
  • 41,230
  • 6
  • 33
  • 58
  • Ok thank you. So if I understand correctly, the checked argument is silently passed to my doSomething() function, which interprets it as its second argument (boolVariable) ? – Mat4444 Jan 31 '20 at 16:10
  • @Mat4444 exactly, and each signal parameter is considered as a positional "optional" argument. This might look strange because if you don't add any arguments to the doSomething function, it will be work anyway without any warning, while if you manually call it with some arguments it will throw an exception for exceeding arguments, but Qt is able to connect to functions that have less arguments than the signal provides, so if the signal has three arguments and the function accepts only one positional argument, it will work anyway. – musicamante Jan 31 '20 at 16:34