Tryin to understand how QTextDocument works, have a question
In the code below, what I wanted to do is to use QTextDocument to put some text inside a rectangle.
The documentation states that the method "drawContents ( QPainter * p, const QRectF & rect = QRectF() )" will use painter to paint the text inside the rectangle.
But in my code the text is being placed one half outside rectangle and one half inside the rectangle.
Can someone spot what I am doing wrong?
Here is the code. I created a widget called "DocWidget" which I set as the centralWidget in the MainWindow constructor. So when I instantiate DocWidget, the paintEvent gets called.
void DocWidget::paintEvent(QPaintEvent *pe)
QPainter *painter = new QPainter(this);
//Color: #333 QPen fontPen(QColor::fromRgb(51,51,51), 1, Qt::SolidLine); QRectF rectangle(10.0, 20.0, 150.0, 60.0); painter->drawRoundedRect(rectangle, 20.0, 15.0); painter->setPen(fontPen); QTextDocument document; document.setHtml("<p>HELLO</p>"); document.drawContents( painter, rectangle );
to my knowledge, the rectangle passed to drawContents() describes which part of the TextDocument is actually to be drawn.
To define WHERE to draw it, you must use translate():
document.drawContents(painter, QRect(0,0, 150, 60));
To do clipping, you need to set up an appropriate clipping region in your QPainter.
Hope this works for you.