Re: Colour text in a Gtk2::CellRendererText in a Gtk2::TreeView




On Oct 19, 2004, at 7:09 PM, Daniel Kasak wrote:

Some of my users want particular cells in a Gtk2::TreeView to be highlighted in different colours depending on the data. eg if one field has a flag set to 'parent' then another cell should be formatted red, etc.

Is it possible to do this?

absolutely, but it's probably not as pretty as you'd like.

if all of the cells in a column will be the same color, you can do

   $renderer->set (foreground => 'red',   # there's also foreground-gdk
                   foreground_set => TRUE);  # so it gets used

if different rows should have different colors, there are two approaches you can use.


a) calculate the color to use and store it in a column in your Gtk2::TreeModel, and then set up a TreeViewColumn attribute to use that column to set the foreground color.

    $renderer = Gtl2::CellRendererText->new;
    $renderer->set (foreground_set => TRUE);
    $column = Gtk2::TreeViewColumn->new_with_attributes
                                ($title,
                                 $renderer,
                                 text => $text_column_index,
                                 foreground => $color_column_index);


b) or, you can calculate the color on the fly in a cell data function. this can get pretty processing-intensive, but is the only way to handle some extremely dynamic data. the cell data func gets called every time the column goes to draw a cell; its purpose is to set the properties of the cell renderer, so the renderer draws the right stuff.

    $column = Gtk2::TreeViewColumn->new;
    $renderer = Gtk2::CellRendererText->new;
    $renderer->set (foreground_set => TRUE);
    $column->pack_start ($renderer, TRUE);
    $column->set_cell_data_func ($renderer, sub {
                my ($column, $cell, $model, $iter) = @_;
                # use an interesting and sophisticated algorithm to
                # determine what text to display and what color it
                # should be (a la spreadsheet cell functions, where
                # the contents of the cell are not what is displayed)
                my ($text, $color) = do_something_cool ($model, $iter);
                $cell->set (text => $text,
                            foreground => $color);
    });

there's another example of using a cell data func in Gtk2/examples/cellrenderer_popup.pl -- the custom cell data func formats data from a Gtk2::Scalar column in the model, where the scalars are array references; without the cell data func, the renderer shows "ARRAY(0xabcdef)" etc.

the nice thing about the cell data func is that you can do anything you want. the drawback is that it is very easy to make your treeview render sluggishly, so you need to optimize your code there.


--
"Quit hittin' yourself!  Quit hittin' yourself!"
   -- Elysse, playing with a newborn baby.




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]