How to write custom Gtk.CellRenderer in python and

2019-04-07 14:25发布

问题:

i must write my own cell renderer with button, i came up with this:

#!/usr/bin/env python3
from gi.repository import Gtk

class CellRendererButton(Gtk.CellRenderer):
    def __init__(self):
        Gtk.CellRenderer.__init__(self)

    def get_size(self, widget, cell_area):
        buttonHeight = cell_area.height
        buttonWidth = buttonHeight
        return (0, 0, buttonWidth, buttonHeight)

    def render(self, window, widget, background_area, cell_area, expose_area, flags):
        style = widget.get_style()
        x, y, buttonWidth, buttonHeight = self.get_size()
        style.paint_box(window, widget.get_state(), Gtk.SHADOW_ETCHED_OUT, expose_area, widget, None, 0, 0, buttonWidth, buttonHeight)

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title = 'T', default_width = 200, default_height = 300)
        self.connect('destroy', self.__onDestroy)
        self.__createGUI()
        self.show_all()

    def __createGUI(self):
        box = Gtk.Box(orientation = Gtk.Orientation.VERTICAL)
        listStore = Gtk.ListStore(str, str)
        treeView = Gtk.TreeView(listStore)
        textRenderer = Gtk.CellRendererText()
        textColumnA = Gtk.TreeViewColumn(None, textRenderer)
        textColumnB = Gtk.TreeViewColumn(None, textRenderer)
        buttonRenderer = CellRendererButton()
        buttonColumn = Gtk.TreeViewColumn(None, buttonRenderer)
        textColumnA.add_attribute(textRenderer, 'text', 0)
        textColumnB.add_attribute(textRenderer, 'text', 1)
        treeView.append_column(textColumnA)
        treeView.append_column(textColumnB)
        treeView.append_column(buttonColumn)
        listStore.append(('my string', 'my string'))
        self.add(treeView)

    def __onDestroy(self, e):
        Gtk.main_quit()

t = MyWindow()
Gtk.main()

but its not working :/ I get lots of errors like:

(game.py:4736): Gtk-CRITICAL **: gtk_cell_renderer_render: assertion `GTK_CELL_RENDERER_GET_CLASS (cell)->render != NULL' failed

I'm missing something? Is there something more i should do to make it work?

回答1:

You should name your methods do_get_size() and do_render(). These are special names that let GTK know that you are overriding the parent class's virtual method.