Grokking PHP-GTK : GtkTreeView and friends

Submitted by Frederic Marand on Sun, 2006-10-15 19:57

GtkTreeView and related classes in PHP-GTK 2The function of the GtkCTree, GtkCList and other associated components has been overhauled in GTK2, meaning PHP-GTK now has a very thoughtfully detailed mechanism for building trees and lists, more or less following an MVC model. The attached diagram shows the relations between the set of classes involved in laying out a tree or list using GtkTreeView.

Model, View ... Controller ?

The two main classes involved are GtkTreeView, which represents the visual part of the code supplied by GTK, and any class implementing the GtkTreeModel interface, which typically means either GtkTreeStore or GtkListStore amongst the builtin classes.

The class implementing this interface supplies the data store, or in MVC terms the model, to the view widget.

Another relationship, although less obvious because it is indirect is the one linking the columns of the view, implemented by GtkTreeViewColumn, with the store classes for the purpose of sorting the view. For this, the store classes need to implement the GtkTreeSortable, which both of the default store classes supply.

Model, View... but where is the controller ? It is more or less the user-developed code. Why "less" ? Because model and view should not interact directly with each other, but always through the model, while in GTK the view and model classes are in direct relationship, to factor glue code that would otherwise typically be replicated in all controller implementations.

Where are my Rows and Colums ?

The GtkTreeView does not process the model all on its own, but delegates the columnar characteristics of the view to the GtkTreeViewColumn class, which holds the column-specific information, and most importantly the renderer, which is a class derived from GtkCellRenderer, through which the data linked in from the view and column are displayed, possibly edited, and returned to the model according to display and editing rules specific to the column. Renderers typically process a set of related formats, like the text renderer, which processes both strings and numbers.

The row information, which is the one containing the actual data as opposed to their format (metadata) held in the columns, is kept in the data store classes. GtkListStore, for instance, holds them in the very simple form of an array of rows, themselves each an array of values, one value per table cell.

Selecting items

The user selection is delegated to an specific class too, GtkTreeSelection, which is available from the view widget using get_selection() on the GtkTreeView instance.

Sample code

Rather than add yet another example to those already available, I suggest you look at the excellent series available in the PHP-GTK2 cookbook about the GtkTreeView widgets.