Solved QTextDocument : drawContents in a QRectF
-
Hello,
I want create a PDF file with QPdfWriter, QPainter and QTextDocument.
I can draw 3 rectangles for header (with image), body (for the text) and footer (with image), but I can't write the text in the body.
Here is a simple example :
QString fileName = "/Users/charlie/test.pdf"; QPdfWriter pdfWriter(fileName); QPainter painter; pdfWriter.setResolution(300); QPageSize pageSize(QPageSize::A4); QMarginsF margins(10, 10, 10, 10); QPageLayout pageLayout(pageSize, QPageLayout::Portrait, margins, QPageLayout::Millimeter); pdfWriter.setPageLayout(pageLayout); painter.begin(&pdfWriter); QRectF headerRect(0, 0, mm2px(pdfWriter.widthMM()), 100); QRectF bodyRect(0, headerRect.bottom(), mm2px(pdfWriter.widthMM()), 600); painter.setPen(Qt::red); painter.drawRect(headerRect); painter.setPen(Qt::blue); painter.drawRect(bodyRect); QTextDocument td; //painter.translate(bodyRect.x(), bodyRect.y()); td.setHtml("<font size=16>K<sub>max</sub>=K<sub>2</sub> · 3</font>"); td.drawContents(&painter, bodyRect); painter.end(); QDesktopServices::openUrl(QUrl("file:"+fileName));
In this example, the text is not draw, but if replace :
td.drawContents(&painter, bodyRect);
bytd.drawContents(&painter, headerRect);
, this works !!!!
In my case,painter.translate()
don't have effect.I don't understand why. Can you help me ?
Thank you very much in advance.
Charlie.
-
Second parameter to
drawContents
is a clipping rect, not a destination rect i.e. the contents of your text document are clipped to that rectangle. Usingtranslate
is the way to go. Just don't clip the document:painter.translate(bodyRect.topLeft()); td.setHtml("<font size=16>K<sub>max</sub>=K<sub>2</sub> · 3</font>"); td.drawContents(&painter);
-
Hi,
It's work. Thank.
Concerning the second parameter to
drawContent
, I thought it would allow to use a "wrap mode" on my text. But it is not the solution.In fact, this is better with this code :
... QTextOption textOption; textOption.setAlignment(Qt::AlignJustify); textOption.setWrapMode(QTextOption::WordWrap); td.setDefaultTextOption(textOption); td.setTextWidth(bodyRect.width()); td.setHtml(myHtml); ...
Sorry for the inconvenience.
++
Charlie