The model: GtkTreeModel and GtkTreeStore
GtkTreeModel is the interface definition for the model part of
GtkTreeView. The application programmer could define his own model,
but GtkTreeView provides the two most popular ones: a linear list
with GtkListStore, and a hierarchical tree with
GtkTreeStore. The
GtkTreeView reference manual claims that few application programmers
will need to use anything else, and they may well be right. Since I
have little experience with GtkListStore, this article will discuss
GtkTreeStore only.
The first step in using GtkTreeView, then, is to set up a
GtkTreeStore to keep your data. The model contains some number of
rows and each row contains the same number of columns. The cells
in each column contain the same type of data. These columns are
declared when the model is created, though they can be changed later,
if necessary.
Example 10.1. Model
$model = new GtkTreeStore(Gobject::TYPE_PHP_VALUE, Gobject::TYPE_STRING); |
Here we create a GtkTreeStore with two columns. The first
column contains a PHP variable (of any type), the second a
string. There are several different types available, see GType.
We will be using the first column to hold an array
containing all the information about a folder and the second
column to display its name.
It does not matter in which order you define
the columns. The order in which
GtkTreeStore
knows them does not
affect how they are displayed to the user. It is not even necessary
to display all columns to the user.
Nodes can be added to a GtkTreeStore in several ways. My
preference is to use the gtk_tree_store_insert_before function,
known as the insert_before() method in PHP.
Example 10.2. Create Row
$folder = new_folder();
$iter = $model->insert_before(null, null);
$model->set($iter, 0, $folder);
$model->set($iter, 1, $folder['name']); |
This code first inserts an empty row into the model,
then sets the values in both cells for the row.
A GtkTreeModel lets the programmer refer to rows in various
ways. We see here a GtkTreeIter object,
which essentially works as a
pointer to the row. We then use this pointer, plus a column number,
to refer to a cell.
GtkTreeIter objects are also used as arguments to
insert_before() , to define the parent
of the new node,
and the sibling that is to follow the new node. If the parent is NULL,
as in the example above, the new node is added to the top level,
and if sibling is NULL, then the new node becomes
the last child of the parent.
The GtkTreeIter objects may be temporary, and may become
invalidated as the tree is modified by adding or removing nodes. It
is probably a bad idea to store them.
You can also remove rows (gtk_tree_store_remove a.k.a.
$model->remove() ).
For other operations, please see the API reference documentation.