Bind push-button to function

Hello,

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")
  return                                                           
dialog = pya.QDialog.new(pya.Application.instance().main_window())
pya.QPushButton("ok....",dialog).clicked = test()
dialog.show()

Thanks, :)

Comments

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

    Matthias

  • 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.QDialog.new(pya.Application.instance().main_window())
    pya.QCheckBox("Click me", dialog).stateChanged = test
    dialog.show()
    

    You can bind to a function with less arguments too:

    def test():
      print("State changed")
    
    dialog = pya.QDialog.new(pya.Application.instance().main_window())
    pya.QCheckBox("Click me", dialog).stateChanged = test
    dialog.show()
    

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

    def test(buttonName):
      print("Clicked: " + buttonName)
    
    dialog = pya.QDialog.new(pya.Application.instance().main_window())
    dialog.layout = pya.QVBoxLayout(dialog)
    b1 = pya.QPushButton("Button 1", dialog)
    dialog.layout.addWidget(b1)
    b1.clicked = lambda: test("B1")
    b2 = pya.QPushButton("Button 2", dialog)
    dialog.layout.addWidget(b2)
    b2.clicked = lambda: test("B2")
    dialog.show()
    

    Matthias

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