Search code examples
pythonpython-3.xpyqtpyqt4

Send several parameters when combo box activated


self.comboBox.activated[str].connect(self.on_combo_activated)

At the moment when a combo box gets selected only the value of the combo box gets passed on to the function on_combo_activated.

How would I do if I wanted to send another two variables?


Solution

  • One way to solve this is by using a lambda function:

    self.comboBox.activated[str].connect(
        lambda text: self.on_combo_activated(text, 'str1', 'str2'))
    ...
    
    def on_combo_activated(self, text, arg1, arg2):
        print(text, arg1, arg2) 
    

    The functools.partial function does something similar, but it can sometimes be awkward to use it with positional arguments. If you used it to connect the above slot like this:

    self.comboBox.activated[str].connect(
        partial(self.on_combo_activated, 'str1', 'str1')
    

    the slot would actually print str1 str2 text, because extra positional arguments are always appended, rather than inserted. However, with keyword arguments, it would work as expected:

    self.comboBox.activated[str].connect(
        partial(self.on_combo_activated, arg1='str1', arg2='str1'))
    

    This last approach might be preferred over the others as it is self-documenting, and therefore perhaps more readable.