代码之家  ›  专栏  ›  技术社区  ›  BPS

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

  •  6
  • BPS  · 技术社区  · 11 年前

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

    #!/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 回复  |  直到 11 年前
        1
  •  5
  •   ptomato    11 年前

    你应该命名你的方法 do_get_size() do_render() 。这些是特殊的名称,可以让GTK知道您正在重写父类的虚拟方法。