Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paint correct text color in QStyledItemDelegate

I'd like to draw a custom item delegate, which follows the current style. But there are differences between "WindowsVista/7" style and "WindowsClassic" for text color.

difference between winViste/7 and winClassic

Im using the following code for drawing the background (working):

void FriendItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    painter->save();

    QStyleOptionViewItem opt = option;
    initStyleOption(&opt, index);
    QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();
    QSize hint = sizeHint(opt, index);

    style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget);
    ...
}

How to draw the text in correct color?

I can't use style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); to draw the whole item, because I have to draw more special text than one text line. (This function would paint the colors correctly.)

I tried with style->drawItemText(painter, opt.rect, opt.displayAlignment, opt.palette, true, "Hello World!"); but it paints always black. And for painter->drawText(), I have no idea how to set the correct pen color.

like image 852
Schlumpf Avatar asked Sep 30 '22 03:09

Schlumpf


1 Answers

The doc for QStyle::drawItemText says:

If an explicit textRole is specified, the text is drawn using the palette's color for the given role.

You can use it like this inside your delegate paintEvent:

QString myText = ...;

QPalette::ColorRole textRole = QPalette::NoRole;
if (option.state & QStyle::State_Selected)
{
    textRole = QPalette::HighlightedText;
}

qApp->style()->drawItemText(painter, opt.rect, opt.displayAlignment, 
                            opt.palette, true, myText, textRole);
like image 171
hank Avatar answered Oct 17 '22 06:10

hank