Using partial to create slots for signals with return values in PyQt

Go To StackoverFlow.com

1

I have a dictionary whose keys are the names of all the dials in my PyQT interface. The values associated with these keys are certain numeric values associated with each dial that need to be passed to a handler function (to determine which dial was moved), along with the new value of that dial.

I've used functools.partial to create a different instance of the handler function for each of the numeric values, but the "valueChanged" signal returns an integer and I'm not sure how to pass it into the partial function as well. The following doesn't seem to work, as the dialChanged function ends up never being called:

for dial, cc, in dialDict.iteritems():
    getattr(self.ui, dial).setRange(0,127)
    getattr(self.ui, dial).valueChanged.connect(
        lambda value: partial(self.windowHandler.dialChanged, 
                              mainWindowInstance=self, 
                              cc=cc, 
                              value=value))

I think the problem has to do with the use of the lambda function inside the for loop and scope, but I'm not sure how to otherwise go about passing the return value of the valueChanged signal into the slot created by partial. Any suggestions would be appreciated.

2012-04-04 00:38
by Bitrex
What's the signature of dialChanged - Niklas B. 2012-04-04 00:40


2

I actually think it does make sense to use partial here, and ditch the lambda, but to make your dialChanged handler have a callback friendly signature:

# where ever this is defined
def dialChanged(value, mainWindowInstance=None, cc=None):
    pass

cbk = partial(
    self.windowHandler.dialChanged, 
    mainWindowInstance=self, 
    cc=cc)

.valueChanged.connect(cbk)

The slot is going to be called with a value arg, so this should line up with the signature I would think. The lambda is only necessary if you don't have control over that dialChanged slot function and you need to completely reformat the signature by wrapping around the call.

2012-04-04 00:56
by jdi
Great! That works perfectly. Thanks - Bitrex 2012-04-04 01:04
@Bitrex: My experience with PyQt to date is that partial pretty much always solves my callback needs. I never use lambdas for the callbacks - jdi 2012-04-04 01:06
Ads