Important: Please read the Qt Code of Conduct -

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 with QPainter::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:

    1. Use QString::left to extract whatever first characters are default-colored and draw them.
    2. Call setPen with the color for the differently-colored character.
    3. Calculate the rect for the first part of the string using QFontMetrics::boundingRect.
    4. Draw the odd character using bounding rect from 4. as offset.
    5. Add the offset for the odd letter the same way.
    6. 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.

  • Hi! How about the following:

    void MyWidget::paintEvent(QPaintEvent*)
        QPainter painter(this);
        QTextDocument doc;
        doc.setHtml("<font color=\"#f00\">H</font>allo");

  • 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 with QTextDocument::drawContents?

  • @Violet-Giraffe Sure, just apply transformations to the painter as you wish.

  • Oh, you can translate the painter after drawing to it! Neat!

Log in to reply