如何自定义在 `Gtk.TreeViewColumn` 中呈现的文本?

How to customize text rendered in a `Gtk.TreeViewColumn`?

我将文件大小(以字节为单位)存储在 Gtk.ListStore 中,并希望它们由 Gtk.CellRendererText 以人类可读的格式呈现。阅读文档,似乎 Gtk.TreeViewColumn.set_cell_data_func() 是实现此目的的方法。设置它没有错误,但是一旦要渲染一个单元格,整个应用程序就会在几次断言失败后崩溃。

这是我正在使用的代码:

self._builder.get_object("ContentList.Size").set_cell_data_func(
    Gtk.CellRendererText(),
    self.render_formatted_size
)

这是打印到 stderr 的内容:

/usr/lib/python3.7/site-packages/gi/overrides/Gio.py:44: Warning: g_object_freeze_notify: assertion 'G_IS_OBJECT (object)' failed
  return Gio.Application.run(self, *args, **kwargs)
/usr/lib/python3.7/site-packages/gi/overrides/Gio.py:44: Warning: g_object_get: assertion 'G_IS_OBJECT (object)' failed
  return Gio.Application.run(self, *args, **kwargs)
/usr/lib/python3.7/site-packages/gi/overrides/Gio.py:44: Warning: g_object_set: assertion 'G_IS_OBJECT (object)' failed
  return Gio.Application.run(self, *args, **kwargs)
/usr/lib/python3.7/site-packages/gi/overrides/Gio.py:44: Warning: g_object_is_floating: assertion 'G_IS_OBJECT (object)' failed
  return Gio.Application.run(self, *args, **kwargs)
/usr/lib/python3.7/site-packages/gi/overrides/Gio.py:44: Warning: g_object_get_qdata: assertion 'G_IS_OBJECT (object)' failed
  return Gio.Application.run(self, *args, **kwargs)

self.render_formatted_size 的内容在这里应该无关紧要。好像从来没有执行过。

PS:向模型添加额外的字符串列不是一种选择,因为我希望能够随时更改显示单位(SI、IEC)。

您传递了一个新创建的 CellRenderer,而不是现有的。应该这样做:

rend = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("title", rend)
column.set_cell_data_func (rend, cell_fn, None);
tree.append_column(column)