Search code examples
gtk3pygobjectcellrenderer

How to limit number of decimal places to be displayed in Gtk CellRendererText


I am trying to limit the amount of decimal places shown in a Gtk.CellRendererText. Currently a float number field is shown with 6 decimal places, but I would like to have just 1.

enter image description here

This test code should work on Linux:

#!/usr/bin/python3
from gi.repository import Gtk

class MyWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Hello World")
        self.set_default_size(200, 200)

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

        self.liststore.append([9.9])
        self.liststore.append([1])

        xrenderer = Gtk.CellRendererText()
        xrenderer.set_property("editable", True)
        xcolumn = Gtk.TreeViewColumn("Float Numbers", xrenderer, text=0)
        xcolumn.set_min_width(100)
        xcolumn.set_alignment(0.5)
        treeview.append_column(xcolumn)

        self.add(treeview)

win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

Solution

  • Tripped over the same problem. Basically what you want to do is use your GtkTreeViewColumn's set_cell_data_func to set the rendering function, which changes the 'text' property of the cell. In terms of your example, try adding the line:

    xcolumn.set_cell_data_func(xrenderer, \
        lambda col, cell, model, iter, unused:
            cell.set_property("text", "%g" % model.get(iter, 0)[0]))
    

    References: