TreeModel
Object Hierarchy:
Description:
The TreeModel interface defines a generic tree interface for use by the TreeView widget.
It is an abstract interface, and is designed to be usable with any appropriate data structure. The programmer just has to implement this interface on their own data type for it to be viewable by a TreeView widget.
The model is represented as a hierarchical tree of strongly-typed, columned data. In other words, the model can be seen as a tree where every
node has different values depending on which column is being queried. The type of data found in a column is determined by using the GType system
(ie. INT, GTK_TYPE_BUTTON
,
POINTER, etc). The types are homogeneous per column across all nodes. It is
important to note that this interface only provides a way of examining a model and observing changes. The implementation of each individual
model decides how and if changes are made.
In order to make life simpler for programmers who do not need to write their own specialized model, two generic models are provided — the TreeStore and the ListStore. To use these, the developer simply pushes data into these models as necessary. These models provide the data structure as well as all appropriate tree interfaces. As a result, implementing drag and drop, sorting, and storing data is trivial. For the vast majority of trees and lists, these two models are sufficient.
Models are accessed on a node/column level of granularity. One can query for the value of a model at a certain node and a certain column on that node. There are two structures used to reference a particular node in a model. They are the TreePath-struct and the TreeIter -struct (“iter” is short for iterator). Most of the interface consists of operations on a TreeIter-struct.
A path is essentially a potential node. It is a location on a model that may or may not actually correspond to a node on a specific model. The TreePath-struct can be converted into either an array of unsigned integers or a string. The string form is a list of numbers separated by a colon. Each number refers to the offset at that level. Thus, the path `0` refers to the root node and the path `2:4` refers to the fifth child of the third node.
By contrast, a TreeIter-struct is a reference to a specific node on a specific model. It is a generic struct with an integer and three generic pointers. These are filled in by the model in a model-specific way. One can convert a path to an iterator by calling get_iter. These iterators are the primary way of accessing a model and are similar to the iterators used by TextBuffer. They are generally statically allocated on the stack and only used for a short time. The model interface defines a set of operations using them for navigating the model.
It is expected that models fill in the iterator with private data. For example, the ListStore model, which is internally a simple linked list, stores a list node in one of the pointers. The TreeModelSort stores an array and an offset in two of the pointers. Additionally, there is an integer field. This field is generally filled with a unique stamp per model. This stamp is for catching errors resulting from using invalid iterators with a model.
The lifecycle of an iterator can be a little confusing at first. Iterators are expected to always be valid for as long as the model is unchanged (and doesn’t emit a signal). The model is considered to own all outstanding iterators and nothing needs to be done to free them from the user’s point of view. Additionally, some models guarantee that an iterator is valid for as long as the node it refers to is valid (most notably the TreeStore and ListStore). Although generally uninteresting, as one always has to allow for the case where iterators do not persist beyond a signal, some very important performance enhancements were made in the sort model. As a result, the ITERS_PERSIST flag was added to indicate this behavior.
To help show some common operation of a model, some examples are provided. The first example shows three ways of getting the iter at the location `3:2:5`. While the first method shown is easier, the second is much more common, as you often get paths from callbacks.
Acquiring a TreeIter-struct
// Three ways of getting the iter pointing to the location
GtkTreePath *path;
GtkTreeIter iter;
GtkTreeIter parent_iter;
// get the iterator from a string
gtk_tree_model_get_iter_from_string (model,
&iter,
"3:2:5");
// get the iterator from a path
path = gtk_tree_path_new_from_string ("3:2:5");
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_path_free (path);
// walk the tree to find the iterator
gtk_tree_model_iter_nth_child (model, &iter,
NULL, 3);
parent_iter = iter;
gtk_tree_model_iter_nth_child (model, &iter,
&parent_iter, 2);
parent_iter = iter;
gtk_tree_model_iter_nth_child (model, &iter,
&parent_iter, 5);
This second example shows a quick way of iterating through a list and getting a string and an integer from each row. The populate_model
function used below is not shown, as it is specific to the ListStore. For
information on how to write such a function, see the ListStore documentation.
Reading data from a TreeModel
enum
{
STRING_COLUMN,
INT_COLUMN,
N_COLUMNS
};
...
GtkTreeModel *list_store;
GtkTreeIter iter;
gboolean valid;
gint row_count = 0;
// make a new list_store
list_store = gtk_list_store_new (N_COLUMNS,
G_TYPE_STRING,
G_TYPE_INT);
// Fill the list store with data
populate_model (list_store);
// Get the first iter in the list, check it is valid and walk
// through the list, reading each row.
valid = gtk_tree_model_get_iter_first (list_store,
&iter);
while (valid)
{
gchar *str_data;
gint int_data;
// Make sure you terminate calls to gtk_tree_model_get() with a “-1” value
gtk_tree_model_get (list_store, &iter,
STRING_COLUMN, &str_data,
INT_COLUMN, &int_data,
-1);
// Do something with the data
g_print ("Row %d: (%s,%d)\n",
row_count, str_data, int_data);
g_free (str_data);
valid = gtk_tree_model_iter_next (list_store,
&iter);
row_count++;
}
e TreeModel interface contains two methods for reference counting:
ref_node and
unref_node. These two methods are optional to implement. The
reference counting is meant as a way for views to let models know when nodes are being displayed.
TreeView will take a reference on a node when it is visible, which means the node is
either in the toplevel or expanded. Being displayed does not mean that the node is currently directly visible to the user in the viewport. Based
on this reference counting scheme a caching model, for example, can decide whether or not to cache a node based on the reference count. A
file-system based model would not want to keep the entire file hierarchy in memory, but just the folders that are currently expanded in every
current view.
When working with reference counting, the following rules must be taken into account:
- Never take a reference on a node without owning a reference on its parent. This means that all parent nodes of a referenced node must be referenced as well.
- Outstanding references on a deleted node are not released. This is not possible because the node has already been deleted by the time the row-deleted signal is received.
- Models are not obligated to emit a signal on rows of which none of its siblings are referenced. To phrase this differently, signals are only required for levels in which nodes are referenced. For the root level however, signals must be emitted at all times (however the root level is always referenced when any view is attached).
Example: TreeModel:
public class MyNode : Object {
// Data:
public int id { get; set; }
public string name { get; set; }
public int price { get; set; }
public int stock { get; set; }
public MyNode (int id, string name, int price, int stock) {
this.price = price;
this.stock = stock;
this.name = name;
this.id = id;
}
}
public class MyModel : Object, Gtk.TreeModel {
private GenericArray<MyNode> data;
private int stamp = 0;
public MyModel (owned GenericArray<MyNode>? data = null) {
if (data == null) {
this.data = new GenericArray<MyNode> ();
} else {
this.data = (owned) data;
}
}
public void add (int id, string name, int price, int stock) {
data.add (new MyNode (id, name, price, stock));
stamp++;
}
public Type get_column_type (int index) {
switch (index) {
case 0:
case 2:
case 3:
return typeof (int);
case 1:
return typeof (string);
default:
return Type.INVALID;
}
}
public Gtk.TreeModelFlags get_flags () {
return 0;
}
public void get_value (Gtk.TreeIter iter, int column, out Value val) {
assert (iter.stamp == stamp);
MyNode node = data.get ((int) iter.user_data);
switch (column) {
case 0:
val = Value (typeof (int));
val.set_int (node.id);
break;
case 1:
val = Value (typeof (string));
val.set_string (node.name);
break;
case 2:
val = Value (typeof (int));
val.set_int (node.price);
break;
case 3:
val = Value (typeof (int));
val.set_int (node.stock);
break;
default:
val = Value (Type.INVALID);
break;
}
}
public bool get_iter (out Gtk.TreeIter iter, Gtk.TreePath path) {
if (path.get_depth () != 1 || data.length == 0) {
return invalid_iter (out iter);
}
iter = Gtk.TreeIter ();
iter.user_data = path.get_indices ()[0].to_pointer ();
iter.stamp = this.stamp;
return true;
}
public int get_n_columns () {
// id, name, price, stock
return 4;
}
public Gtk.TreePath? get_path (Gtk.TreeIter iter) {
assert (iter.stamp == stamp);
Gtk.TreePath path = new Gtk.TreePath ();
path.append_index ((int) iter.user_data);
return path;
}
public int iter_n_children (Gtk.TreeIter? iter) {
assert (iter == null || iter.stamp == stamp);
return (iter == null)? data.length : 0;
}
public bool iter_next (ref Gtk.TreeIter iter) {
assert (iter.stamp == stamp);
int pos = ((int) iter.user_data) + 1;
if (pos >= data.length) {
return false;
}
iter.user_data = pos.to_pointer ();
return true;
}
public bool iter_previous (ref Gtk.TreeIter iter) {
assert (iter.stamp == stamp);
int pos = (int) iter.user_data;
if (pos >= 0) {
return false;
}
iter.user_data = (--pos).to_pointer ();
return true;
}
public bool iter_nth_child (out Gtk.TreeIter iter, Gtk.TreeIter? parent, int n) {
assert (parent == null || parent.stamp == stamp);
if (parent == null && n < data.length) {
iter = Gtk.TreeIter ();
iter.stamp = stamp;
iter.user_data = n.to_pointer ();
return true;
}
// Only used for trees
return invalid_iter (out iter);
}
public bool iter_children (out Gtk.TreeIter iter, Gtk.TreeIter? parent) {
assert (parent == null || parent.stamp == stamp);
// Only used for trees
return invalid_iter (out iter);
}
public bool iter_has_child (Gtk.TreeIter iter) {
assert (iter.stamp == stamp);
// Only used for trees
return false;
}
public bool iter_parent (out Gtk.TreeIter iter, Gtk.TreeIter child) {
assert (child.stamp == stamp);
// Only used for trees
return invalid_iter (out iter);
}
private bool invalid_iter (out Gtk.TreeIter iter) {
iter = Gtk.TreeIter ();
iter.stamp = -1;
return false;
}
}
public class Application : Gtk.Window {
public Application () {
// Prepare Gtk.Window:
this.title = "My Gtk.TreeModel";
this.window_position = Gtk.WindowPosition.CENTER;
this.destroy.connect (Gtk.main_quit);
this.set_default_size (350, 70);
// Model:
MyModel model = new MyModel ();
model.add (1, "hallo" , 10, 100);
model.add (2, "welt", 20, 50);
model.add (3, "!!", 20, 50);
GenericArray<MyNode> data = new GenericArray<MyNode> ();
data.add (new MyNode (1, "hallo" , 10, 100));
data.add (new MyNode (2, "welt", 20, 50));
data.add (new MyNode (3, "!!", 20, 50));
// View:
Gtk.TreeView view = new Gtk.TreeView.with_model (model);
view.insert_column_with_attributes (-1, "ID", new Gtk.CellRendererText (), "text", 0);
view.insert_column_with_attributes (-1, "Name", new Gtk.CellRendererText (), "text", 1);
view.insert_column_with_attributes (-1, "Price", new Gtk.CellRendererText (), "text", 2);
view.insert_column_with_attributes (-1, "Stock", new Gtk.CellRendererSpin (), "text", 3);
this.add (view);
}
public static int main (string[] args) {
Gtk.init (ref args);
Application app = new Application ();
app.show_all ();
Gtk.main ();
return 0;
}
}
valac --pkg gtk+-3.0 Gtk.TreeModel.vala