将 Gtk.Label 放入 Gtk.TreeView 行

Puting Gtk.Label in Gtk.TreeView row

我尝试将标记文本(可能包含斜体、粗体、颜色)放在 Gtk.TreeView 列中,使用以下示例:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk


class CellRendererLabelWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Gtk.Label in Gtk.ListStore Example")


        # Creating the ListStore object
        self.liststore = Gtk.ListStore(str, Gtk.Label)

        # Making the ListStore Model
        label=Gtk.Label()
        label.set_markup("<b>baz</b> foo")
        self.liststore.append(["bar", label])

        treeview = Gtk.TreeView(model=self.liststore)

        # Preparing the first column only plain text
        renderer_text_0 = Gtk.CellRendererText()
        column_text_0 = Gtk.TreeViewColumn("Text", renderer_text_0, text=0)
        treeview.append_column(column_text_0)

        # Preparing the second column with label
        renderer_text_1 = Gtk.CellRendererText()
        column_text_1 = Gtk.TreeViewColumn("Label", renderer_text_1, text=1)
        treeview.append_column(column_text_1)


        self.add(treeview)


win = CellRendererLabelWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

我收到以下错误消息:

GtkLabelInGtkList.py:43: Warning: unable to set property 'text' of type 'gchararray' from value of type 'GtkLabel'
  win.show_all()
GtkLabelInGtkList.py:44: Warning: unable to set property 'text' of type 'gchararray' from value of type 'GtkLabel'
  Gtk.main()

以及下面的window效果图:

如您所见,当我期待“baz foo”之类的内容时,“标签”列行是空的。

如错误消息所述,Gtk 尝试在 GtkLabel 中查找 属性 text,但没有找到。因此,我将 text 替换为 label 以使行像这样 column_text_1 = Gtk.TreeViewColumn("Label", renderer_text_1, label=1)。但随后出现以下错误:

(GtkLabelInGtkList.py:10013): Gtk-WARNING **: Cannot connect attribute 'label' for cell renderer class 'GtkCellRendererText' since attribute does not exist

那么将 Label(或其他 Gtk 的小部件)放入 TreeView 中的解决方案是什么?

不能将小部件放入 GtkTreeView 中,只能放置单元格渲染器。

如果要在树视图列中显示标记,可以使用 GtkCellRendererTextmarkup property 而不是 text 属性:

self.liststore = Gtk.ListStore(str, str)
self.liststore.append(["bar", "<b>baz</b> foo"])

# ...

column_text_0 = Gtk.TreeViewColumn("Text", renderer_text_0, text=0)
column_text_1 = Gtk.TreeViewColumn("Markup", renderer_text_1, markup=1)