Capítulo 4. Creating a Tree View

In order to display data in a tree view widget, we need to create one first, and we need to instruct it where to get the data to display from.

A new tree view is created with:

  GtkWidget *view;

  view = gtk_tree_view_new();

4.1. Connecting Tree View and Model

Before we proceed to the next section where we display data on the screen, we need connect our data store to the tree view, so it knows where to get the data to display from. This is achieved with gtk_tree_view_set_model, which will by itself do very little. However, it is a prerequisite for what we do in the following sections. gtk_tree_view_new_with_model is a convenience function for the previous two.

gtk_tree_view_get_model will return the model that is currently attached to a given tree view, which is particularly useful in callbacks where you only get passed the tree view widget (after all, we do not want to go down the road of global variables, which will inevitably lead to the Dark Side, do we?).

4.1.1. Reference counting

Tree models like GtkListStore and GtkTreeStore are GObjects and have a reference count of 1 after creation. The tree view will add its own reference to the model when you add the model with gtk_tree_view_set_model, and will unref it again when you replace the model with another model, unset the model by passing NULL as a model, or when the tree view is destroyed. [1]

This means that you need to take care of "your" reference yourself, otherwise the model will not be destroyed properly when you disconnect it from the tree view, and its memory will not be freed (which does not matter much if the same model is connected to the tree view from application start to end). If you plan to use the same model for a tree view for the whole duration of the application, you can get rid of "your" reference right after you have connected the model to the view - then the model will be destroyed automatically when the tree view is destroyed (which will be automatically destroyed when the window it is in is destroyed):

  GtkListStore *liststore;
  GtkWidget    *view;

  view = gtk_tree_view_new();

  liststore = gtk_list_store_new(1, G_TYPE_STRING);

  gtk_tree_view_set_model(GTK_TREE_VIEW(view), GTK_TREE_MODEL(liststore));


  /* Now the model will be destroyed when the tree view is destroyed */



'Reference counting' means that an object has a counter that can be increased or decreased (ref-ed and unref-ed). If the counter is unref-ed to 0, the object is automatically destroyed. This is useful, because other objects or application programmers only have to think about whether they themselves are still using that object or not, without knowing anything about others also using it. The object is simply automatically destroyed when no one is using it any more.