[PyKDE] Pythons slots? how?

Green, Gregory P gregory.p.green at boeing.com
Wed Sep 4 00:27:01 BST 2002


I have always used the following method. It works, that doesn't mean there
isn't a better way. Keep a dictionary mapping menu id's to functions instead
of a big if/elif/else statement.

untested
class FruitMenu(QPopupMenu):
    def __init__(self):
        QPopupMenu.__init__(self)
	  self.menu_actions = {}
        id = self.insertItem('apple')
        self.menu_actions[id] = self.apple
        id = self.insertItem('orange')
        self.menu_actions[id] = self.orange
        QObject.connect(self, SIGNAL('activated(int)'), self.handleChoice)
    def handleChoice(self, id):
        self.menu_actions[i]()
    def apple(self): print 'apple'
    def orange(self): print 'orange'

You can also use getattr and apply with the names of the functions instead.

id = self.insertItem('apple')
self.menu_actions[id] = 'apple'

in handleChoice:
apply(getattr(self.menu_actions[i], (self,))

-----Original Message-----
From: Burley, Brent [mailto:Brent.Burley at disney.com]
Sent: Tuesday, September 03, 2002 3:10 PM
To: pykde at mats.gmd.de
Subject: [PyKDE] Pythons slots? how?


Is it possible to define a new slot in python?  I know I can connect a Qt
signal to a python callable via QObject.connect(), but is it possible to
define a true Qt slot that can be referenced in other situations?

In particular, I'd like to make a menu where each item calls a different
method:

from qt import *
import sys

class FruitMenu(QPopupMenu):
    def __init__(self):
        QPopupMenu.__init__(self)
        self.insertItem('apple', self, SLOT('apple()'))
        self.insertItem('orange', self, SLOT('orange()'))
    def apple(self): print 'apple'
    def orange(self): print 'orange'

app = QApplication(sys.argv)
main = QMainWindow()
fm = FruitMenu();
main.menuBar().insertItem('fruit', fm)
main.show()
app.setMainWidget(main)
app.exec_loop()

But this doesn't work since apple and orange are not Qt slots.  And I can't
use QObject connect in this context since I can't get at the signal for each
individual menu item.  The only way I know to make this work is to connect
to the generic 'activated' signal:

class FruitMenu(QPopupMenu):
    def __init__(self):
        QPopupMenu.__init__(self)
        self.apple_id = self.insertItem('apple')
        self.orange_id = self.insertItem('orange')
        QObject.connect(self, SIGNAL('activated(int)'), self.handleChoice)
    def handleChoice(self, id):
        if id == self.apple_id: self.apple()
        elif id == self.orange_id: self.orange()
    def apple(self): print 'apple'
    def orange(self): print 'orange'

This method works, but it's a little more cumbersome, especially when the
menu is large and/or dynamic.

Thanks,

	Brent Burley

_______________________________________________
PyKDE mailing list    PyKDE at mats.gmd.de
http://mats.gmd.de/mailman/listinfo/pykde




More information about the PyQt mailing list