[Interest] Scaling QTextDocument into a drawing region

Bob Hood bhood2 at comcast.net
Sat Feb 18 17:18:02 CET 2017


I guess scaling the font is the best approach for this niche problem.  I've 
decided an intelligent application of both font scaling and text eliding will 
solve the issueuntil something better comes along.


On 2/17/2017 11:13 AM, Bob Hood wrote:
> I want to wrangle HTML-formatted text contained in a QTextDocument into a 
> specific drawing region, but I want it drawn there scaled-to-fit instead of 
> broken-to-fit.  I'm not gettingthat, and I'm scratching my head.
>
> Some code for discussion:
>
>     ...
>     QTextDocument td;
>     td.setDocumentMargin(0);
>     td.setPageSize(QSize(bounds.width(), bounds.height()));
>     td.setTextWidth(bounds.width());
>     td.setHtml(tr("<center>This is just a long line of text I want to 
> display</center>"));
>
>     painter.save();
>     painter.translate(bounds.left(), bounds.top());
>
>     QAbstractTextDocumentLayout::PaintContext ctx;
>     ctx.palette.setColor(QPalette::Text, painter.pen().color());
>     td.documentLayout()->draw(&painter, ctx);
>
>     painter.restore();
>     ...
>
> Now, if the width of "bounds" is smaller than the document's layout, it of 
> course breaks the line to make it fit. However, what I want it to do is 
> /scale/the text to fit the width of "bounds" so that it all appears on a 
> single line without breakage.
>
> I've tried a number of different approaches to get the QTextDocument to 
> actually scale to "bounds" if it exceeds it, including inserting " ", 
> which just causes breakage in non-obvious locations, and using the QPainter 
> to try scaling the drawing area, but that gives me ugly text, even with 
> small scaling factors.
>
> The one I've seemed to have the most success with is:
>
>     ...
>     QFont f = td.defaultFont();
>     for(;;)
>     {
>         doc_size = td.documentLayout()->documentSize();
>         if(doc_size.width() < new_bounds.width())
>             break;
>
>         f.setPointSizeF(f.pointSizeF() - .1);
>         td.setDefaultFont(f);
>     }
>     ...
>
> But of course the font size can only go so low before setPointSizeF() starts 
> failing, so I have to lock the lowest font size, even if it doesn't result 
> in the text fitting within "bounds".
>
> Is this approach of manipulating the font size the best way of getting a 
> QTextDocument to scale within an arbitrary boundary, or is there something 
> else I might try manipulating (QAbstractTextDocumentLayout?) to get me 
> closer to my goal?
>
>
>
> _______________________________________________ Interest mailing list 
> Interest at qt-project.org http://lists.qt-project.org/mailman/listinfo/interest

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20170218/b44897c2/attachment.html>


More information about the Interest mailing list