GTK+ 2.0 Tree View Tutorial | ||
---|---|---|
<<< Previous | Chapter 5. Mapping Data to the Screen: GtkTreeViewColumn and GtkCellRenderer | Next >>> |
This seems to be a frequently asked question, so it is worth mentioning it here. You have the two approaches mentioned above: either you use cell data functions, and check in each whether a particular row should be highlighted in a particular way (bold, coloured, whatever), and then set the renderer properties accordingly (and unset them if you want that row to look normal), or you use attributes. Cell data functions are most likely not the right choice in this case though.
If you only want every second line to have a gray background to make it easier for the user to see which data belongs to which line in wide tree views, then you do not have to bother with the stuff mentioned here. Instead just set the rules hint on the tree view as described in the here, and everything will be done automatically, in colours that conform to the chosen theme even (unless the theme disables rule hints, that is).
Otherwise, the most suitable approach for most cases is that you add two columns to your model, one for the property itself (e.g. a column COL_ROW_COLOR of type G_TYPE_STRING), and one for the boolean flag of the property (e.g. a column COL_ROW_COLOR_SET of type G_TYPE_BOOLEAN). You would then connect these columns with the "foreground" and "foreground-set" properties of each renderer. Now, whenever you set a row's COL_ROW_COLOR field to a colour, and set that row's COL_ROW_COLOR_SET field to TRUE, then this column will be rendered in the colour of your choice. If you only want either the default text colour or one special other colour, you could even achieve the same thing with just one extra model column: in this case you could just set all renderer's "foreground" property to whatever special color you want, and only connect the COL_ROW_COLOR_SET column to all renderer's "foreground-set" property using attributes. This works similar with any other attribute, only that you need to adjust the data type for the property of course (e.g. "weight" would take a G_TYPE_INT, in form of a PANGO_WEIGHT_FOO define in this case).
As a general rule, you should not change the text colour or the background colour of a cell unless you have a really good reason for it. To quote Havoc Pennington: "Because colors in GTK+ represent a theme the user has chosen, you should never set colors purely for aesthetic reasons. If users don't like GTK+ gray, they can change it themselves to their favorite shade of orange."
<<< Previous | Home | Next >>> |
A Working Example | Up | How to Pack Icons into the Tree View |