Capítulo 11. Writing Custom Models

11.1. When is a Custom Model Useful?

A custom tree model gives you complete control over your data and how it is represented to the outside (e.g. to the tree view widget). It has the advantage that you can store, access and modify your data exactly how you need it, and you can optimise the way your data is stored and retrieved, as you can write your own functions to access your data and need not rely solely on the gtk_tree_model_get. A model tailored to your needs will probably also be a lot faster than the generic list and tree stores that come with gtk and that have been designed with flexibility in mind.

Another case where a custom model might come in handy is when you have all your data already stored in an external tree-like structure (for example a libxml2 XML tree) and only want to display that structure. Then you could write a custom model that maps that structure to a tree model (which is probably not quite as trivial as it sounds though).

Using a custom model you could also implement a filter model that only displays certain rows according to some filter criterion instead of displaying all rows (Gtk+-2.4 will have a filter model, GtkTreeModelFilter, that does exactly that and much more, but you might want to implement this yourself anyway).

However, all this comes at a cost: you are unlikely to write a useful custom model in less than a thousand lines, unless you strip all newline characters. Writing a custom model is not as difficult as it might sound though, and it may well be worth the effort, not least because it will result in much saner code if you have a lot of data to keep track of.