FAQ Index - Search - Recent Changes - Everything - Add entry

<< Previous Entry | FAQ Entry 13.45 | Next Entry >>

13.45. How do I create a custom gtk.CellRenderer?

In order to render custom objects in TreeViews you have to subclass the gtk.GenericCellRenderer class and register it.

The following example shows a CellRenderer for a custom object.

 class CellRendererCustom(gtk.GenericCellRenderer):
        __gproperties__ = {
                "custom": (gobject.TYPE_OBJECT, "Custom",
                "Custom", gobject.PARAM_READWRITE),

        def __init__(self):
                self.custom = None

        def do_set_property(self, pspec, value):
                setattr(self, pspec.name, value)

        def do_get_property(self, pspec):
                return getattr(self, pspec.name)

        def on_render(self, window, widget, background_area, cell_area, expose_area, flags):
                self.custom.draw(window, widget, cell_area.x, cell_area.y)

        def on_get_size(self, widget, cell_area=None):
                return (0, 0, self.custom.get_width(), self.custom.get_height())

Note that in order to use the custom object in e. g. a ListStore you'll have to subclass it from gobject.GObject and register it properly.

Notice however that in more recent pygtk versions it is possible to subclass a predefined CellRenderer type instead of starting from scratch from GenericCellRenderer; in this case you just have to overwrite methods of the form do_*: for instance the following creates a CellRenderer for text which cells twice as big as normal:

 class CellRendererBig(gtk.CellRendererText):

     def __init__(self):

     def do_get_size(self, widget, cell_area):
         # We start from the standard dimension...
         size_tuple = gtk.CellRendererText.do_get_size(self, widget, cell_area)
         size = [item * 2 for item in size_tuple]
         return tuple(size)      

Jiri Bajer: draw() method in on_render is deprecated - use self.widget.window.draw_rectangle() instead. See [www.mail-archive.com] for details.

PyGTK FAQ Wizard | PyGTK Homepage | Feedback to faq at pygtk.org