How can I modify the color for individual words for items in a view?
Answer:
In order to change the color for only some of the words or characters in an item, you need to draw the item yourself. This can be done by subclassing QItemDelegate and reimplementing paint() to draw the text using QPainter::drawText(). See the documentation:
http://doc.trolltech.com/qitemdelegate.html#paint
http://doc.trolltech.com/qpainter.html#drawText-9
The example below demonstrates how this can be done:
#include <QtGui>
class ItemDelegate: public QItemDelegate
{
public:
ItemDelegate()
{
}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex & index ) const
{
if(index.row() == 0 ) {
QRect r;
painter->drawText(option.rect,Qt::TextSingleLine, "Item ",
&r);
painter->setPen(Qt::red);
QRect modOptRect = option.rect;
modOptRect.setLeft(option.rect.left() + r.width());
painter->drawText(modOptRect, "1");
} else {
QItemDelegate::paint(painter, option, index);
}
}
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QTreeWidget tree;
tree.setItemDelegate(new ItemDelegate());
QTreeWidgetItem *item1= new QTreeWidgetItem();
QTreeWidgetItem *item2= new QTreeWidgetItem();
item2->setText(0, "item 2");
tree.addTopLevelItem(item1);
tree.addTopLevelItem(item2);
tree.show();
return app.exec();
}