PDA

View Full Version : Painting Rich Text



xanthine
14th April 2006, 20:34
Hi,

I want to paint HTML-formatted text with a QPainter. In Qt3, this was easily done with QSimpleRichText - but I am not sure what the equivalent method is in Qt4.

I have tried using the QTextLayout class, but without success. This code, for example, does not appear to draw anything:


QTextLayout l( "test" );
l.draw( qPainter, QPointF( 0, 0 ) );

I have tried passing a font to QTextLayout in its constructor, changing the pen used in QPainter, etc, but none of these changes has resulted in drawn text.

Any ideas on where I'm going wrong? :)

jacek
14th April 2006, 21:03
IMO you must help it a bit with the layout process:
QTextLayout l( "test" );
l.beginLayout();
QTextLine line = l.createLine();
line.setLineWidth( 100 );
line.setPosition( QPointF( 0, 14 ) );
l.endLayout();
l.draw( qPainter, QPointF( 100, 100 ) );

xanthine
14th April 2006, 21:15
Excellent - that works perfectly!

Thanks Jacek :)

xanthine
14th April 2006, 21:24
Another issue - the painted text isn't formatted according to the HTML tags; instead, the text is printed as plain text (including the tags).

I couldn't see any options in QTextLayout documentation for specifying the formatting of the text - only a reference to using it as part of a QTextDocument..

So how do I make it format it as rich text (using HTML tags to achieve the formatting isn't important)?

jacek
14th April 2006, 23:31
As the docs say:
The QTextLayout class is used to lay out and paint a single paragraph of text.
...
The class has a rather low level API and unless you intend to implement your own text rendering for some specialized widget, you probably won't need to use it directly.
Try QTextDocument::documentLayout() and QAbstractTextDocumentLayout::draw().

xanthine
15th April 2006, 21:25
Thanks for the tip, Jacek.

However, I can't get anything to appear via QAbstractTextDocumentLayout::draw(). For example, here is some test code that doesn't work:


QTextDocument td( "test" );
QAbstractTextDocumentLayout::PaintContext ctx;
ctx.clip = QRectF( 0, 0, 400, 100 );
qPainter->drawRect( ctx.clip ); // Test that I'm drawing in the right area
td.documentLayout()->draw( qPainter, ctx );

The clip rectangle gets drawn properly, but no text is drawn.

I've tried looking at how QTextEdit draws its QTextDocument, and I can't see anything significantly different to what I am doing, but obviously there must be something..

Any ideas?

jacek
15th April 2006, 22:09
Add:
td.setPageSize( QSizeF( 400, 100 ) );Probably you need also:
td.documentLayout()->setPaintDevice( this );

xanthine
16th April 2006, 00:35
It's all working perfectly now. Thanks for all your help!