The problem is that you are creating a function using lambda
where some of the variables inside the function are not being passed in as arguments to the function. When the lambda function is executed, when the signal is emitted, it uses the value of those variables (like instance
) at that moment in time. To be clear, every lambda function you make is using the value of instance
at runtime, rather than define time. So instance
only holds a reference to the object used in the last iteration of our loop, which explains the behaviour you are seeing.
Some useful information can be found here (read the comments too) http://eli.thegreenplace.net/2011/04/25/passing-extra-arguments-to-pyqt-slot/
From the comments of the above link:
What you can do is have another function generate the lambda, i.e.
something like:
def make_callback(param):
return lambda: self.on_button(param)
And in the connection, call make_callback(i)
. Then a different lambda is
created for each iteration.
So you would want to generalise this and pass in things like instance
to the make_callback
function and then place your lambda
definition inside the make_callback
function. I would provide a clear example of this, but as the other answer says, your formatting appears to have become very messed up in your question and I would likely get it wrong for your specific application. If you aren't following what I've said, make the code in your question clearer and I'll have a go at creating an example!