Q:

Displaying a QStandardItem with its foreground color in a QTreeView even when it is selected

Using Qt 4.6.3 on Linux/X11.
I have a QTreeView widget which uses a QStandardItemModel as its model, with 4 columns and hundreds of rows. Most of the items in the list are to be displayed with a standard color, but a few need to be of a different color. I can change the colors of those few items easily with QStandardItem::setForeground().
However, that only affects the color of the item when it is not selected. When I select a colored item, its background color changes to blue (which is ok), and the text color changes to white (which is not ok). I tried using a stylesheet to affect the foreground color of selected items (with selector QTreeView::item:selected), but it affects all items.
I would like items for which I called item->setForeground(Qt::red) to remain red even when they are selected, and other items to use the default set of colors (which they already do). How can that be done?

A:

The colors being used are (I assume) those for the QPalette's Hightlight and HighlightedText roles.  Unfortunately, I don't know of any way to set those on an individual standard item.
However, since standard items are used in the model/view framework, you have another option.  You should be able to create a delegate to paint the view however you want to.  I would recommend inheriting from the styled delegate, and calling the parent class's functionality as much as possible.  Likely, you'll only need to change a few parameters in the cases where an item is selected and has a non-standard foreground color.

