【问题标题】:How to inherit from GObject class?如何从 GObject 类继承?
【发布时间】:2015-11-23 16:09:34
【问题描述】:

我想编写一个带有树视图小部件的应用程序,我将存储我的“项目”类的对象。

我知道为了做到这一点,我的“Item”类必须继承自 GObject 类。不幸的是,出了点问题,我在树上看不到项目的文本。我只收到这个警告:

Warning: unable to set property 'text' of type 'gchararray' from value of type '__main__+Item'

我必须做些什么来解决这个问题?

此示例程序用于演示问题,已准备好测试修复:

#!/usr/bin/env python3

from gi.repository import Gtk
from gi.repository import GObject


class Item(GObject.GObject):
    text = GObject.property(type=str, default='item', flags=GObject.PARAM_READWRITE)

    def __init__(self, title):
        GObject.GObject.__init__(self)
        self.__title = title

    def __str__(self):
        return self.__title

GObject.type_register(Item)


class MainWindow(Gtk.Window):
    def __init__(self):
        super().__init__(Gtk.WindowType.TOPLEVEL)
        self.connect('destroy', self.on_destroy)
        tree_model = Gtk.TreeStore(Item.__gtype__)
        # tree_model = Gtk.TreeStore(str)
        text_renderer = Gtk.CellRendererText()
        text_column = Gtk.TreeViewColumn(None, text_renderer)
        text_column.add_attribute(text_renderer, 'text', 0)
        tree_view = Gtk.TreeView(tree_model)
        tree_view.append_column(text_column)
        self.add(tree_view)
        self.show_all()
        tree_model.append(None, (Item('test'),))
        # tree_model.append(None, ('It works!',))

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


if __name__ == '__main__':
    MainWindow()
    Gtk.main()

【问题讨论】:

    标签: python gtk pygobject gobject


    【解决方案1】:

    GtkCellRendererTexttext 属性需要字符串 (gchararray) 数据,并且它正在接收自定义 GObject 值。 __str__ 函数在 Python 级别上工作,GObject 永远不会调用。

    幸运的是,您想要实现的目标不需要子类化 GObject。您需要执行以下操作:

    • 将树存储列指定为GObject.TYPE_PYOBJECT。这将允许您将实例附加到树存储,而无需继承 GObject 或特殊属性。

    • 在树视图列上使用 set_cell_data_func 从存储在模型中的实例中提取文本数据。

    请参阅 this answer 了解该技术的工作示例。

    【讨论】:

    • 我也在尝试这样做,但我不能在创建树视图后立即使用set_cell_data_func(缺少应该稍后动态附加的数据)。只要不使用set_cell_data_func,警告仍然显示是否正常?
    • @zezollo 如果数据丢失,那么您的数据函数应该返回空字符串(或任何合适的字符串,直到可用为止)。问题中的警告表明程序包含错误。
    猜你喜欢
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 2010-11-24
    • 1970-01-01
    相关资源
    最近更新 更多