Search code examples
htmlqtqtextdocument

Setting QTextDocument painter's rectangle (where to paint)


I am painting on a window simple html using QTextDocument::drawContents(painter)

I want to do the drawing inside some margins in the window but I don't see a direct way to specify the target rectangle of the painting (in the painter/window).

I guess a few ways to do it:

  • Using the QTextDocuments::setMargin (although this does not allow different values for left/top.

  • Placing the html into an styled <div>

  • Applying a translation transform to the painter.

But all this seems a bit too much for what I want to do and I guess if I a missing something straight (as you do with QPainter::drawText where you tell the target rectangle)


Solution

  • Set the textWidth property to the width of the area where the text is supposed to fit. The clipping rectangle you pass to drawContents will cut the text off vertically if there's too much of it to fit; you can't do much about that of course.

    So, this would be the missing function you're after:

    void drawContents(QPainter * p, QTextDocument & doc, const QRectF & rect) {
      p->save();
      p->translate(rect.topLeft());
      doc.setTextWidth(rect.width());
      doc.drawContents(p, rect);
      p->restore();
    }
    

    Yes, you do need to jump through a few hoops, that's why it needs to be factored out. It's perhaps lamentable that a similar overload of drawContents doesn't exist.