GTK+ 2.0 Tree View Tutorial using Ocaml | ||
---|---|---|
Prev | Chapter 3. GTree.models for Data Storage: GTree.list_store and GTree.tree_store | Next |
Rows can easily be removed with GTree.list_store#remove (gtk_list_store_remove) and GTree.tree_store#remove (gtk_tree_store_remove). The removed row will automatically be removed from the tree view as well.
Removing a single row is fairly straight forward: you need to get the iter that identifies the row you want to remove, and then use one of the above functions. Here is a simple example that removes a row when you double-click on it (bad from a user interface point of view, but then it is just an example):
let on_row_activated view path col = print_endline "Row has been double-clicked. Removing row."; let model = view#model in let iter = model#get_iter path in model#remove iter; (* It returns bool *) () (* We have to return () in callback. *) let create_treeview () = ... treeview#connect#row_activated ~callback:(on_row_activated treeview); ...
Note: GTree.list_store#remove (gtk_list_store_remove) and GTree.tree_store#remove (gtk_tree_store_remove) both have slightly different semantics in Gtk+-2.0 and Gtk+-2.2 and later. In Gtk+-2.0, both functions do not return a value, while in later Gtk+ versions those functions return either true or false to indicate whether the iter given has been set to the next valid row (or invalidated if there is no next row). (The current LablGTK2 supports Gtk+-2.4 and remove method returns true or false.) This is important to keep in mind when writing code that is supposed to work with all Gtk+-2.x versions. In that case you should just ignore the value returned (as in the call above) and check the iter with GTree.list_store#iter_is_valid (gtk_list_store_iter_is_valid) if you need it.
If you want to remove the n-th row from a list (or the n-th child of a tree node), you have two approaches: either you first create a GtkTreePath that describes that row and then turn it into an iter and remove it; or you take the iter of the parent node and use iter_children method (gtk_tree_model_iter_nth_child) (which will also work for list stores if you use None as the parent iter). Of course you could also start with the iter of the first top-level row, and then step-by-step move it to the row you want, although that seems a rather awkward way of doing it.
The following code snippet will remove the n-th row of a list if it exists:
(****************************************************************** * * list_store_remove_nth_row * * Removes the nth row of a list store if it exists. * * Returns true on success or false if the row does not exist. * ******************************************************************) let list_store_remove_nth_row store n = try let iter = store#iter_children ~nth:n None in store#remove iter; true with Invalid_arg _ -> false