Search code examples
htmlqtqt4qstringqpainter

paint text with paintEvent()


i have a program that needs to paint some text with paintEvent(). i've tried this:

1. QPainter painter; // painter for the canvas
2. painter.drawText(QPoint location, QString canvasText);

where

3. QString canvasText = variablesText.append("< b >");
4. variablesText.append((*fieldIter).second.c_str());
5. variablesText.append(":< /b > ");
6. variablesText.append(someValue);
7. variablesText.append("\n");

I need the text to be formated, canvasText should look like:

Some bold text: some not bold text. (newLine)

Some bold text 2: some not bold text2. (newLine) and that goes on for a while.

The problem i'm having is that a QString can't have HTML code in it, so the text is displayed like:

< b>Some bold text:< /b> some not bold text. < b>Some bold text 2: < /b>
some not bold text2.\n

Is there a way to use draw in paintEvent to show the text the way i need it? with a QString (or QLabel or something)

I'm using Qt4.

Thanks for the help =)


Solution

  • QTextDocument seems like a good fit for what you're after, specifically setHtml(). A QTextDocument can format your text and paint the result to the screen via your widget's QPainter. Something like the below is the simplest possible solution:

    void Test::paintEvent(QPaintEvent *)
    {
      QPainter painter(this);
    
      QTextDocument doc;
      doc.setHtml("<b>Title</b><p>Body Text</p>");
    
      doc.drawContents(&painter, rect());
    }
    

    Bear in mind, however, that this is likely to be very inefficient. You'll probably want to drawContents() to a cached QPixmap only when your source html changes...