[PyKDE] PyQt not refing slot methods - bug?

Burley, Brent Brent.Burley at disney.com
Fri Aug 30 17:52:01 BST 2002


Boudewijn Rempt wrote:
> On Thursday 29 August 2002 21:02, Burley, Brent wrote:
> > Is it a bug that PyQt isn't refing slot methods?  Doesn't anyone use
> > lambdas for slots?
> 
> I don't think it's a bug -- it's certainly behaviour I would expect of
> PyQt, and no, I never use lambda's for slots. I feel a bit silly right now,
> because I can't think why using lambda is better than:
> 
> def hello(): print 'hello'
> QObject.connect(b, SIGNAL('clicked()'), hello)

I use lambda in a callback when I want to bind arguments to it.  Consider:

import sys           
from qt import *
def buttonPressed(n): print 'button %d pressed' %n
app = QApplication(sys.argv)
box = QVBox()
lambdaRefs = []
for i in range(1,11):
    b = QPushButton(str(i), box)
    l = lambda i=i: buttonPressed(i)
    lambdaRefs.append(l) # keep ref since Pyqt won't 
    QObject.connect(b, SIGNAL('clicked()'), l)
app.setMainWidget(box)
box.show()
app.exec_loop()


If you don't use lambda, you either have to subclass the pushbutton or make a separate function object for each button.  Lambda is often simpler.  Note: if you were to use a function object, you would have the same problem as with the lambda in that you would have to hold the reference yourself.

Lambdas are often used in Tkinter code for this purpose and Tkinter does in fact ref the lambda.  Here's a page describing this:  http://effbot.org/zone/tkinter-callbacks.htm  Also, John Grayson discusses it and uses it extensively in "Python and Tkinter Programming".

The fact that PyQt doesn't ref the slot method means that the common lambda/command object callback idiom does not work.  This sort of behavior creates bugs that can be very difficult to find.  [There's a similar behavior in Tkinter where setting an image on a label doesn't ref the image; this
caused me a great deal of grief!]

Given that the behavior of PyQt is as intended (and Phil's justification seems reasonable), and given that the use of lambdas (or command objects) is natural and common, especially for people coming from Tkinter, perhaps a note on the PyQt Signals and Slots page is warranted.

	Brent




More information about the PyQt mailing list