FOX Community

Recent site activity

Cookbook‎ > ‎

Setting different text colors for list items

Problem

The FXList class provides a setTextColor() member function to set the (single) color for all list items' text, but you want to use a variety of colors for the items in a list.

Solution

The first step is to create a new class derived from FXListItem and override its virtual draw() member function. See attachment: ColoredListItem.h

The ColoredListItem constructor and the setTextColor() and getTextColor() member functions are self-explanatory. Our overloaded draw() member function is heavily based on the original FXListItem version (which you can inspect in the FOX source code). In fact, the only difference comes in that last bit that actually draws the label text for this item:

if(!label.empty()){
dc.setTextFont(list->getFont());
if(!isEnabled())
dc.setForeground(makeShadowColor(list->getBackColor()));
else if(state&SELECTED)
dc.setForeground(list->getSelTextColor());
else
dc.setForeground(getTextColor()); // THIS IS DIFFERENT
dc.drawText(x,y+(h-th)/2+list->getFont()->getFontAscent(),label.text(),label.length());
}
The next-to-last line (marked with the comment THIS IS DIFFERENT) sets the drawing color to this item's text color. The original version (from the FXListItem source code) instead uses the color returned by the list's getTextColor() member function. If you take a step back and look over the rest of our custom draw() function, you'll see some other properties that could be easily customized as well (such as the selection and background colors, and the text font).

Finally, you need to make sure the list uses ColoredListItem objects instead of regular FXListItem objects to populate the list. One way to do this is use the overloaded versions of appendItem(), prependItem(), insertItem() and replaceItem() that expect pointers to FXListItem objects. For example, instead of adding new items like this:

aList->appendItem("Red");
aList->appendItem("Blue");
aList->appendItem("Green");

Do this instead:

ColoredListItem *redItem=new ColoredListItem("Red");
redItem->setTextColor(FXRGB(255,0,0));

ColoredListItem *greenItem=new ColoredListItem("Green");
greenItem->setTextColor(FXRGB(0,255,0));

ColoredListItem *blueItem=new ColoredListItem("Blue");
blueItem->setTextColor(FXRGB(0,0,255));

aList->appendItem(redItem);
aList->appendItem(greenItem);
aList->appendItem(blueItem);

Contribution(s)

Lyle Johnson



Attachments (1)

  • ColoredListItem.h - on Aug 15, 2008 6:48 PM by Sander Jansen (version 1)
    2k Download