Search code examples
pythonpygtkgobject

Using enum properties in PyGTK/GObject


This tutorial on using GObject in Python only covers using a property of type gobject.TYPE_FLOAT.

I've adapted it to use an enumerated type:

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

FUEL_NONE = 0
FUEL_SOME = 1
FUEL_FULL = 2

class Car(gobject.GObject):
  __gproperties__ = {
       'fuel' : (gobject.TYPE_ENUM,                         # type
                 'fuel of the car',                         # nick name
                 'amount of fuel that remains in the tank', # description
                 FUEL_SOME,                                 # default value
                 gobject.PARAM_READWRITE)                   # flags
  }

# <<rest of demo code>>

...but when I attempt to run it I get the following error:

/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py:114: Warning: g_param_spec_enum: assertion `g_enum_get_value (enum_class, default_value) != NULL' failed
  type_register(cls, namespace.get('__gtype_name__'))
Traceback (most recent call last):
  File "gcar.py", line 9, in <module>
    class Car(gobject.GObject):
  File "/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py", line 60, in __init__
    cls._type_register(cls.__dict__)
  File "/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py", line 114, in _type_register
    type_register(cls, namespace.get('__gtype_name__'))
TypeError: Error when calling the metaclass bases
    could not create param spec for type GEnum (while registering property 'fuel' for GType '__main__+Car')

What am I missing?


Solution

  • It's not enough enough to tell __gproperties__ that it's an enumerated type; you need to register the enumeration with the GObject type system, and then use the GType value you get from that instead of gobject.TYPE_ENUM. At least, that's how it's done in C. I'm not sure what the proper way to do this is PyGTK is, but it might involve writing a .defs file and running pygobject-codegen-2.0 on it.

    Of course, it's probably easier to just make the property of type gobject.TYPE_INT with a minimum and maximum value that matches the bounds of your enum, unless you really need the GObject system to understand the details of your enumeration.