[pygtk] Subclassing GObject and virtual functions

Samuel Cormier-Iijima sciyoshi at gmail.com
Sat Aug 12 12:33:29 WST 2006


The thing is, I'm writing a library that I'd like to be easily usable
from Python, and not involve the user with the GObject internals. So
far, I've gotten this to work by wrapping the generated class with
some python code.

class Foo(_Foo):
   def __new__(cls):
      gobject.type_register(cls)
      return gobject.GObject.__new__(cls)

This allows the user to do something simple like this:

class SubFoo(lib.Foo):
   def do_on_connected(self):
      print 'hi'

a = SubFoo()
a.do_something_that_calls_on_connected_from_vfunc_table()

and have it output 'hi'. Otherwise, the user needs to do stuff like

class SubFoo(lib.Foo):
   __metaclass__ = gobject.GObjectMeta
   def do_on_connected(self):
      print 'hi'

Are there any better options, and what's the Right Thing to do here?

Again, thanks for all the help.

Cheers,
Samuel

On 8/11/06, Johan Dahlin <jdahlin at async.com.br> wrote:
> Samuel Cormier-Iijima skrev:
> > Hi John,
> >
> > Thanks for the reply :-) I've gotten it to work with these virtual
> > functions, however the python code is ugly with the required call to
> > gobject.type_register and using signals for the vfuncs (you have to
> > subclass and implement the method do_on_connected and define
> > __gsignals__ instead of just implementing on_connected). I'm not sure
> > how hard this would be to implement, are there plans under way to
> > allow for things like this?
> Signal overrides are different from virtual methods.
> The support for overriding virtual methods is relatively new in PyGTK,
> It was introduced
> in 2.6 unless I'm mistaken.
>
> You'll only need to define __gsignals__ if you want to override a
> signal, it is not necessary to implement a virtual method. However, you
> should always call gobject.type_register for the subclass even though
> it's not always necessary, it's of good practice.
>
> In other words, to override say expose event, do this:
>
> class MyWidget(gtk.Widget):
>    def do_expose_event(self, event):
>       pass
> gobject.type_register(MyWidget)
>
> For a complete example of a custom widget check out the
> examples/gtk/widget.py file in pygtk cvs/tarball.
>
> Johan
>
>
>


More information about the pygtk mailing list