Forum und email

GtkTreeView Tutorial (basic)

Introduction

Thanks to Lars Wirzenius for the original version of this tutorial written for PyGtk. Changes to the document were only to reflect the current state of the Gtk+ codebase and to be applicable to PHP-Gtk2.

Version 2.0 of Gtk+ introduces its third generation of tree and list widgets. Version 1.0 had GtkList and GtkTree, version 1.2 had GtkCList and GtkCTree, and now version 2.0 has GtkTreeView, which servers both as a list and a tree. With each version, the power and usefulness of the widgets have increased.

GtkTreeView uses a Model/View/Controller approach. This means that the code is divided into a data structure representing user's data ("the model"), the widgets that display the data and interact with the user ("the view"), and some logic to tie things nicely together ("the controller"). The model is implemented by GtkTreeModel (actually, classes implementing that interface), the view by GtkTreeView with some helpers, and the controller by the user code.

This sounds unnecessarily complicated, but the complexity is local, and this aproach actually simplifies overall program structure. For example, it is often necessary to view the same data (i.e., model) in different ways, or in different windows. Think, for example, of a programmer's editor: the same source code may be viewed in several windows at the same time, and changes in one window should be shown in all the others, as well. Thus, it makes sense to separate the storage of the text from its display, rather than storing the text in each window widget.

The example application in this article lets the user manage a folder tree. The folders are virtual, not real directories in the filesystem, to keep the code simpler. The example is actually derived from Lodju, in which the folders have nothing to do with the filesystem.

The official Gtk+ 2.0 API reference documentation for GtkTreeView should be read together with this tutorial, even if it is a bit sparse in some details.

I thank the people on the Gtk+ developer IRC channel for encouragement and feedback.