[Qt-interest] Paint a QTextDocument with a Custom Pen

Josiah Bryan jbryan at productiveconcepts.com
Sat Oct 10 01:00:30 CEST 2009


Josiah Bryan wrote:
> Evening, All -
> 
> I'd like to draw a QTextDocument in a QGraphicsItem using a custom pen 
> (e.g. to outline the text with, say, a 3px black outline to set it off 
> from the background.) E.g.:
> 
> // Begin Snippet
>    // m_text is a QTextDocument with HTML set using setHtml()  
> 
>    QPen pen;
>    pen.setWidthF(3);
>    pen.setColor(QColor(0,0,0,200));
>    QBrush brush(QColor(255,255,255,200));
>    painter->setPen(pen);
>    painter->setBrush(brush);
> 
>     QAbstractTextDocumentLayout::PaintContext pCtx;
>     m_text->documentLayout()->draw(painter, pCtx);
> // End Snippet
> 
> Now, ideally, that would render with a 3px black border and white text. 
> Of course, as we all know, HTML can spec its own text color inline - 
> which would imply that the documentLayout() overrides the pen already 
> set on the provided painter.

I'm shocked no one new this one! Once I learned more about editing rich 
text with Qt, its Rich Text cursor editing and character formats 101. 
Here's how I finally did it:


QTextCharFormat format;
format.setTextOutline(QPen(Qt::black,1.5));
format.setForeground(Qt::white);

// m_text is a QTextDocument with the HTML already loaded
QTextCursor cursor(m_text);
cursor.select(QTextCursor::Document);
cursor.mergeCharFormat(format);


Hope that helps someone out there on this planet or the next.

Cheers!
-josiah




More information about the Qt-interest-old mailing list