12

A PyQt button event can be connected in the normal way to a function so that the function receives the default signal arguments (in this case the button checked state):

def connections(self):
    my_button.clicked.connect(self.on_button)

def on_button(self, checked):
    print checked   # prints "True"

Or, the default signal arguments can be overridden using lambda:

def connections(self):
    my_button.clicked.connect(lambda: self.on_button('hi'))

def on_button(self, message):
    print message   # prints "hi"

Is there a nice way to keep both signal arguments so it can be directly received by a function like below?

def on_button(self, checked, message):
    print checked, message   # prints "True, hi"
101
  • 8,514
  • 6
  • 43
  • 69
  • You can subclass the button and create a new signal which will emit the state of a button and a message. – SnoozeTime Jun 29 '16 at 04:31
  • [Eli Bendersky](https://eli.thegreenplace.net) posted [an article about this](https://eli.thegreenplace.net/2011/04/25/passing-extra-arguments-to-pyqt-slot) in 2011. – delrocco Nov 09 '17 at 18:11

1 Answers1

30

Your lambda could take an argument:

def connections(self):
    my_button.clicked.connect(lambda checked: self.on_button(checked, 'hi'))

def on_button(self, checked, message):
    print checked, message   # prints "True, hi"

Or you could use functools.partial:

# imports the functools module
import functools 

def connections(self):
    my_button.clicked.connect(functools.partial(self.on_button, 'hi'))

def on_button(self, message, checked):
    print checked, message   # prints "True, hi"
The Compiler
  • 11,126
  • 4
  • 40
  • 54