pythongtkgtk3pygtkgtktreeview

Puting Gtk.Label in Gtk.TreeView row


I try to put markuped text (potentially containing italic, bold, color) in a Gtk.TreeView column, using the following example:

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

And I get the following error message:

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()

And the following window rendering:

First window render image

As you see, the “Label” column row is empty when I was expecting something like “baz foo”.

As the error message said, Gtk try to find the property text in GtkLabel and doesn’t find it. So, I replace text into label to make the line like this column_text_1 = Gtk.TreeViewColumn("Label", renderer_text_1, label=1). But then I get the following error:

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

So what is the solution to put a Label (or other Gtk’s widgets) inside a TreeView?


Solution

  • You cannot put widgets inside a GtkTreeView, only cell renderers.

    If you want to show markup inside a tree view column, you can use the markup property of GtkCellRendererText instead of the text property:

    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)