Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Unsolved Easiest way to paint one letter of the text different color with QPainter::drawText?

    General and Desktop
    2
    5
    1855
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • V
      Violet Giraffe last edited by Violet Giraffe

      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.

      1 Reply Last reply Reply Quote 0
      • ?
        A Former User last edited by

        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);
        }
        
        1 Reply Last reply Reply Quote 4
        • V
          Violet Giraffe last edited by Violet Giraffe

          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?

          ? 1 Reply Last reply Reply Quote 0
          • ?
            A Former User @Violet Giraffe last edited by

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

            1 Reply Last reply Reply Quote 2
            • V
              Violet Giraffe last edited by

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

              1 Reply Last reply Reply Quote 0
              • First post
                Last post