PyQt, Python 3: Lambda slot assigning signal argument to a variable?

2.7k views Asked by At

Assuming the following PyQt signal:

value_changed = pyqtSignal(value)

Is there a way to write a lambda slot that would assign the value provided by the signal to a certain variable, as in this (obviously illegal) example:

object1.value_changed.connect(lambda val: var1=val) 
object2.value_changed.connect(lambda val: var2=val) 
...

What would be the most concise way of achieving such behavior? I would basically like to avoid defining a function for each such assignment.

1

There are 1 answers

2
three_pineapples On BEST ANSWER

I don't think you can (or should want to) do this with lambda. See the answer to the possible duplicate (that I reference under your question) for what you can do.

One way to do something similar would be to simply define a single function which takes two arguments. The value, and some identifier you can use to look up the variable inside the function (eg an object reference or a string).

I might suggest:

object1.value_changed.connect(lambda val: store_var('var1', val)) 
object2.value_changed.connect(lambda val: store_var('var2', val)) 

How you implement store_var() of course is highly dependent on the rest of yoru code structure, whether you want to store the values in a dictionary or as global variables or instance attributes. But you shouldn't have any problem accessing the storage location from within your function if you were expecting to be able to access them from within a lambda expression.


Update

Based on your comment I assume the calls to the connect function are inside a method of the class that contains data. This you would define a method of that class as

def store_var(self, name, value):
    setattr(self.data, name, value)

and then you would call

object1.value_changed.connect(lambda val: self.store_var('var1', val))