PDA

View Full Version : [SOLVED] Different color letters in QComboBox entries



T4ng10r
19th February 2014, 08:55
I would like to draw QComboBox items letters in different color. Lets assume that I have "Test12" entry and "st" in it I want to be bold red and rest to be plain black.
So to make think easier - "Te<b>st</b>12" (or whichever other tag to mark letters). I created QItemDelegate with paint method.

inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
int correction(0);
QStyleOptionViewItemV4 myOption = option;
QPalette standard_color = myOption.palette;
QPalette special_color = myOption.palette;
myOption.textElideMode = Qt::ElideNone;
QFontMetrics font_metric(myOption.font);
special_color.setColor(QPalette::WindowText, QColor(Qt::red));

QString text = "Teno<b>st</b>1989";
int start_pos(0), prev_pos(0), current_width(0);
std::string word;
while((start_pos=text.indexOf(start_tag, prev_pos))>=0)
{
myOption.text = text.mid(prev_pos, start_pos-prev_pos);
//draw in standard color
myOption.palette = standard_color;
myOption.rect.setLeft(current_width);
myOption.rect.setWidth(font_metric.width(myOption. text)+correction);
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &myOption, painter);
current_width += myOption.rect.width();
prev_pos = start_pos+start_tag.size();

start_pos=text.indexOf(end_tag, prev_pos);
myOption.text = text.mid(prev_pos, start_pos-prev_pos);
myOption.palette = special_color;
myOption.rect.setLeft(current_width);
myOption.rect.setWidth(font_metric.width(myOption. text)+correction);
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &myOption, painter);
current_width += myOption.rect.width();
prev_pos = start_pos+end_tag.size();
}
myOption.text = text.mid(prev_pos);
myOption.palette = standard_color;
myOption.rect.setLeft(current_width);
myOption.rect.setWidth(font_metric.width(myOption. text));
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &myOption, painter);
}


Unfortunately - CE_ItemViewItem do not only write text but also frame. I tried QStyle::drawItemText, but I'm still not satisfied. How else could I do it?

anda_skoa
19th February 2014, 10:22
What about letting CE_ItemViewItem not see any text, i.e. keeping myOption.text empty, and the drawing the text yourself?

Cheers,
_

T4ng10r
19th February 2014, 11:54
Yes, this approach do what I expect.