GTK+ By Example/Tree View/Components

From Wikibooks, open books for an open world
< GTK+ By Example‎ | Tree View
Jump to navigation Jump to search

The most important concept underlying GtkTreeView is that of complete separation between data and how that data is displayed on the screen. This is commonly known as Model/View/Controller-design (MVC). Data of various type (strings, numbers, images, etc.) is stored in a 'model'. The 'view' is then told which data to display, where to display it, and how to display it. One of the advantages of this approach is that you can have multiple views that display the same data (a directory tree for example) in different ways, or in the same way multiple times, with only one copy of the underlying data. This avoids duplication of data and programming effort if the same data is re-used in different contexts. Also, when the data in the model is updated, all views automatically get updated as well.

So, while GtkTreeModel is used to store data, there are other components that determine which data is displayed in the GtkTreeView and how it is displayed. These components are GtkTreeViewColumn and GtkCellRenderer. A GtkTreeView is made up of tree view columns. These are the columns that users perceive as columns. They have a clickable column header with a column title that can be hidden, and can be resized and sorted. Tree view columns do not display any data, they are only used as a device to represent the user-side of the tree view (sorting etc.) and serve as packing widgets for the components that do the actual rendering of data onto the screen, namely the GtkCellRenderer family of objects (I call them 'objects' because they are not GtkWidgets). There are a number of different cell renderers that specialise in rendering certain data like strings, pixbufs, or toggle buttons. More on this later.

Cell renderers are packed into tree view columns to display data. A tree view column needs to contain at least one cell renderer, but can contain multiple cell renderers. For example, if one wanted to display a 'Filename' column where each filename has a little icon on the left indicating the file type, one would pack a GtkCellRendererPixbuf and a GtkCellRendererText into one tree view column. Packing renderers into a tree view column is similar to packing widgets into a GtkHBox.