How to paint correct text color in QStyledItemDelegate
Asked Answered
B

2

7

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.

Better answered 6/8, 2014 at 9:2 Comment(4)
If you need to only color the text, you can avoid using item delegates and use QAbstractItemModel::setData() with Qt::ForegroundRole.Mckelvey
I don't want to draw text with a specific text color. I want to draw text with the text color of the current style.Better
Current style of what? Show your QSS.Leifleifer
I have no QSS. I just want to paint the text of the selected item BLACK for "Windows Vista/7" themes and WHITE for "Windows classic" themes, like the image in the question. (Of cause, it should work for all other OS to...)Better
A
4

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);
Assets answered 1/9, 2014 at 14:11 Comment(0)
I
0

Works for me:

if (option.state & QStyle::State_Selected && 
    option.state & QStyle::State_Active)
    painter->setPen(option.palette.color(QPalette::HighlightedText));
else 
    painter->setPen(option.palette.color(QPalette::Text));

painter->drawText(textRect, title, textOption);
Insecticide answered 30/3, 2022 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.