[PyKDE] Pythons slots? how?

Burley, Brent Brent.Burley at disney.com
Wed Sep 4 00:11:01 BST 2002


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




More information about the PyQt mailing list