Search code examples
c++11gtkmmgtkmm3

Is it possible to instruct a `Gtk::TreeView` to display a custom type?


There is something I don't understand how to do with Gtkmm 3.

I have a custom business type that I have declared like this:

enum class Eurocents : int {};

I would like to render this type into a Gtk::TreeView which has a Gtk::ListStore as model. So I declare a Gtk::TreeModelColumn<Eurocents>, and add it to the model. I then append_column this model column to the Gtk::TreeView with an appropriate title.

I then append_row to the model and set the value corresponding to the column to (Eurocents)100.

The result I get is that the cell is displayed empty. Understandably so, because I would not expect Gtkmm to know how to render my arbitrary type.

I would like to instruct Gtkmm on how to render my type.

I already know how to display Glib types like Glib::ustring and formatting to Glib::ustring for display is possible, but it is not the subject of the question.

Is it possible to code columns that can display arbitrary types like this? And if so, how? What is required for sorting to work?


Solution

  • The most common, and easiest way, is to use a cell_data_func callback. For instance, you can create your own instance of a Gtk::TreeView::Column (the view column), pack a cell renderer (or more) into your Gtk::TreeView::Column, append your Gtk::TreeView::Column to the TreeView with Gtk::TreeView::append_column(), and call set_cell_data_func() on your Gtk::TreeView::Column(): https://developer.gnome.org/gtkmm/stable/classGtk_1_1TreeViewColumn.html#a3469e1adf42e5932ea123ec33e4ce4e1

    You callback would then get the value(s) from the model and set the appropriate values of the properties of the renderer(s).

    Here is an example that shows the use of set_cell_data_func(), as well as showing other stuff: https://developer.gnome.org/gtkmm-tutorial/stable/sec-treeview-examples.html.en#sec-editable-cells-example

    This link should also be useful: https://developer.gnome.org/gtkmm-tutorial/stable/sec-treeview.html.en#treeview-cellrenderer-details

    If you like, Gtk::TreeView::insert_column_with_data_func() makes this a little more concise: https://developer.gnome.org/gtkmm/stable/classGtk_1_1TreeView.html#a595dcc0b503a7c1004c296b82c51ac54

    As for the sorting, you should be able to just call set_sort_func() to specify how the column is sorted: https://developer.gnome.org/gtkmm/stable/classGtk_1_1TreeSortable.html#a3a6454bd0a285324c71edb73e403cb1c

    Then this regular sorting advice should apply: https://developer.gnome.org/gtkmm-tutorial/stable/sec-treeview-sort.html.en