Easiest way to paint one letter of the text different color with QPainter::drawText?
-
I know how to
drawText
(at least the basics), and I know you can change text color withQPainter::setPen
. What I need to do is a bit trickier, though: I need one character somewhere in the middle of the string to be painted different (non-default) color.I suppose I could:
- Use
QString::left
to extract whatever first characters are default-colored and draw them. - Call setPen with the color for the differently-colored character.
- Calculate the rect for the first part of the string using
QFontMetrics::boundingRect
. - Draw the odd character using bounding rect from 4. as offset.
- Add the offset for the odd letter the same way.
setPen
back to default and draw the rest of the string using offset calculated at 5.
It looks a bit shaky, though. For one, I have my doubts that the rects will add up perfectly and that the result will be exactly the same as if I wasn't splitting the text and painted it with a single
drawText
call. - Use
-
Hi! How about the following:
void MyWidget::paintEvent(QPaintEvent*) { QPainter painter(this); QTextDocument doc; doc.setHtml("<font color=\"#f00\">H</font>allo"); doc.drawContents(&painter); }
-
I see what you did there! One problem, though (should have mentioned it in the question): the reason I have to use QPainter in the first place (instead of e. g.
QLabel
) is I need to position the text in a certain way (offset it) inside the widget. Is that doable withQTextDocument::drawContents
? -
@Violet-Giraffe Sure, just apply transformations to the painter as you wish.
-
Oh, you can
translate
the painter after drawing to it! Neat!