如何在python和GTK 3中编写自定义Gtk.CellRenderer?

时间:2013-02-21 09:08:01

标签: python gtk pygtk gtk3 pygobject

我必须用按钮编写自己的单元格渲染器,我想出了这个:

#!/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()

但它不起作用:/我收到很多错误,如:

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

我错过了什么?还有什么我应该做的才能让它发挥作用吗?

1 个答案:

答案 0 :(得分:5)

您应该为方法do_get_size()do_render()命名。这些是特殊的名称,让GTK知道你正在覆盖父类的虚方法。