[PyKDE] menu/actions questions

Christian Bird cbird at metrowerks.com
Wed Feb 12 19:40:00 GMT 2003


On Wednesday 12 February 2003 7:54 am, Garrett G. Hodgson wrote:
> > PyQt doesn't increase the reference count of objects passed as slots, so
> > a lambda function will get garbage collected unless you explicitly save
> > it somewhere.
>
> that did it.  thanks!
>
> i still wonder if there's a better/more standard way of accomplishing this.

I use a class that allows currying aften for issues like yours.  Here's a 
working example that uses this method:


#This creates a callable class, that when called,  calls the function
#that was passed in with the arguments that were passed in, and returns
#the resuls
class Curry:
    #this is a list of references to all Curry classes so that they don't get 
    #garbage collected
    references = []
    def __init__(self, func, *args, **kwargs):
        self.func = func
        self.pending = args[:]
        self.kwargs = kwargs.copy()
        Curry.references.append(self)
    def __call__(self, *args, **kwargs):
        return self.func(*self.pending, **self.kwargs)

#this is the same as above, but when called, it adds the arguments
#that were passed in with the call to the arguments passed in 
#when the class is constructed (very useful for Qt signals!)
class CurryArgs(Curry):
    def __call__(self, *args, **kwargs):
        if kwargs and self.kwargs:
            kw = self.kwargs.copy()
            kw.update(kwargs)
        else:
            kw = kwargs or self.kwargs
        return self.func(*(self.pending + args), **kw)



import sys
from qt import *

class MainWindow( QMainWindow ):
    def __init__( self, parent=None, name=None ):
        QMainWindow.__init__( self, parent, name )
        self.CreateMenuBar()

    def CreateMenuBar( self ):
        fileMenu = QPopupMenu( self )

        fileMenu.insertItem( 'Test 1', self.test1 )
        fileMenu.insertItem( 'Test 2', Curry(self.test2, 'hi there'))

        self.menuBar().insertItem( 'File', fileMenu )

    def test1( self ):
        print 'test 1 fired'

    def test2( self, msg ):
        print 'test 2 says', msg

def main():
    app = QApplication( sys.argv )
    mainWin = MainWindow()
    app.setMainWidget( mainWin )
    mainWin.show()
    app.exec_loop()

main()
-- 
Christian Bird

Metrowerks -- a Motorola company
Linux Solutions Group
Office:  801-805-8042
Cell:  801-367-2007
cbird at metrowerks.com




More information about the PyQt mailing list