Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Bind push-button to function


I would like to bind a QPushButton to a function,

If I run the simple script bellow, I get a "Button clicked" printed when starting the program and no action when clicking on the pushbutton,

what is it that I am missing?

def test():
  print("Button clicked")
dialog =
pya.QPushButton("ok....",dialog).clicked = test()

Thanks, :)


  • Hi jonathan,

    that's simple. It's:

    pya.QPushButton("ok....",dialog).clicked = test

    (not the missing brackets after "test").

    You want to bind the function itself, not the result of the function call (which is "None" and essentially resets the binding).


  • Thanks a lot again Matthias. all make more sense now. :o

    Overall, this would also means that, on the case I want to run a function with arguments, I should either create a new PushButton class with input argument or set the arguments as global variable.

  • edited November 2018

    Hi jonathan,

    what arguments would you like to see? clicked doesn't have arguments, so binding a function with arguments to it does not make sense.

    If you have a signal with a value, simply bind to a function which expects a value:

    def test(state):
      print("State changed to: " + str(state))
    dialog =
    pya.QCheckBox("Click me", dialog).stateChanged = test

    You can bind to a function with less arguments too:

    def test():
      print("State changed")
    dialog =
    pya.QCheckBox("Click me", dialog).stateChanged = test

    If you want to add an argument, you can use lambdas for example:

    def test(buttonName):
      print("Clicked: " + buttonName)
    dialog =
    dialog.layout = pya.QVBoxLayout(dialog)
    b1 = pya.QPushButton("Button 1", dialog)
    b1.clicked = lambda: test("B1")
    b2 = pya.QPushButton("Button 2", dialog)
    b2.clicked = lambda: test("B2")


  • edited November 2018

    Hi, I have only now learned about lambda, thank you so much for the help and the very useful and complete example scripts! :)

Sign In or Register to comment.