Python GTK+: create custom signals

gtkpygtkpython

Is it possible to create new signals in Python GTK+ ?

I'd like a skeleton code example, please.

Best Answer

An excerpt:

Creating your own signals

The other thing you probably want to use when subclassing GObject is define custom signals. You can create your own signals that can be emitted so users of your class can connect to them.

When a signal is emitted a set of closures will be executed. A closure is an abstraction of the callback concept. A closure is the callback itself (a function pointer), the user data (it will be the last parameter to the callback) and another function for cleanup issues, which will not be discussed in this document.

For the sake of this article you don't really need to know the difference between a callback and a closure so both terms will be used. But be advised that this is not totally correct.

As we said before, when a signal is emitted, a set of closures will be executed. One of them is the same one for all the instances of this class and hence its name: the class closure, and the other ones are custom user callbacks. Note that not all the signals need to have a class closure because it is optional.

From, http://www.pygtk.org/articles/subclassing-gobject/sub-classing-gobject-in-python.htm, hope that helps. There is example code on the site and here , a snippet:

import pygtk
pygtk.require('2.0')
import gobject

class Car(gobject.GObject):
    __gproperties__ = {
        'fuel' : (gobject.TYPE_FLOAT, 'fuel of the car',
                  'amount of fuel that remains in the tank',
                  0, 60, 50, gobject.PARAM_READWRITE)
        }

    __gsignals__ = {
        'engine-started' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                            (gobject.TYPE_FLOAT,))
        }

    def __init__(self):
        gobject.GObject.__init__(self)
        self.fuel = 50

    def do_get_property(self, property):
        if property.name == 'fuel':
            return self.fuel
        else:
            raise AttributeError, 'unknown property %s' % property.name

    def do_set_property(self, property, value):
        if property.name == 'fuel':
            self.fuel = value
        else:
            raise AttributeError, 'unknown property %s' % property.name

    def do_engine_started(self, remaining_fuel):
        print '***** Beginning of class closure *****'
        print 'The engine is ready and we still have %f of fuel' % self.fuel
        print '***** End of class closure *****'

    def start(self):
        self.emit('engine-started', self.get_property('fuel'))

gobject.type_register(Car)