5.4. GtkCellRendererText and Integer, Boolean and Float Types

It has been said before that, when using attributes to connect data from the model to a cell renderer property, the data in the model column specified in gtk_tree_view_column_add_attribute must always be of the same type as the data type that the property requires.

This is usually true, but there is an exception: if you use gtk_tree_view_column_add_attribute to connect a text cell renderer's "text" property to a model column, the model column does not need to be of G_TYPE_STRING, it can also be one of most other fundamental GLib types, e.g. G_TYPE_BOOLEAN, G_TYPE_INT, G_TYPE_UINT, G_TYPE_LONG, G_TYPE_ULONG, G_TYPE_INT64, G_TYPE_UINT64, G_TYPE_FLOAT, or G_TYPE_DOUBLE. The text cell renderer will automatically display the values of these types correctly in the tree view. For example:


  enum
  {
    COL_NAME = 0,
    COL_YEAR_BORN,
    NUM_COLS
  };

  liststore = gtk_list_store_new(NUM_COLS, G_TYPE_STRING, G_TYPE_UINT);

  ...

  cell = gtk_cell_renderer_text_new();
  col = gtk_tree_view_column_new();
  gtk_tree_view_column_add_attribute(col, cell, "text", COL_YEAR_BORN);

  ...

Even though the "text" property would require a string value, we use a model column of an integer type when setting attributes. The integer will then automatically be converted into a string before the cell renderer property is set [1].

If you are using a floating point type, ie. G_TYPE_FLOAT or G_TYPE_DOUBLE, there is no way to tell the text cell renderer how many digits after the floating point (or comma) should be rendered. If you only want a certain amount of digits after the point/comma, you will need to use a cell data function.

Notes

[1]

For those interested, the conversion actually takes place within g_object_set_property. Before a certain cell is rendered, the tree view column will call gtk_tree_model_get_value to set the cell renderer properties according to values stored in the tree model (if any are mapped via gtk_tree_view_column_add_attribute or one of the convenience functions that do the same thing), and then pass on the GValue retrieved to g_object_set_property.