[PyKDE] So how do I pass an argument to a function tied to a callback?

Ken Kozman kkozman at zyvex.com
Fri Mar 2 20:27:53 GMT 2001


    I read the first message but did not understand it very well (there is
no accounting for my stupidity) but in reading this most recent message I
think I see what is going on. This is something that I too had problems
with. Basically you want to hook a Qt signal up to a slot, but instead of
just getting any Qt parameters at the signal (which is 0 in the case of
"clicked( )") you want to get some parameter you set at QObject.connect
time, right?

   Or a little more succinctly, as Aaron said, you want but can't do the
following:

    self.connect( widget, SIGNAL( "clicked()" ), self.someFunction( num ) )

    I tried the same thing with lambda and had similar problems, I vaguely
remember a segfault as well, but this was some time ago.

    What I came up with was the following:

    # This is a silly little class to wrap function calling.
    class CCommandDispatcher:
        def __init__( self, function, functionId ):
            self.caller = function
            self.callerId = functionId
        def invoke( self ):
            self.caller( self.callerId )

    # Then later on...
    self.dispatcher = CCommandDispatcher( self.buttonPressed, num )
    self.connect( widget, SIGNAL( "clicked()" ), self.dispatcher.invoke )

    I must admit I only used this for about a day before I modified the
command calling structure in my current application. Obviously the command
dispatcher piece could be made a little more robust. But this "style" also
allows for whatever sort of complexity you might want to allow for at the
button click time, this is just an example of wanting to pass a single
parameter to the call. I don't know tons about Python, but I'm sure this
method is far less efficient than lambda, both in terms of memory usage and
execution time, but it works, or at least it did about a month ago.

    I don't know if this is sufficient for your requirements Aaron.

Ken






More information about the PyQt mailing list