Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Call for Presentations - Qt World Summit

    Drawing a wrapped, justified text inside a rectangle and adjusting line spacing

    General and Desktop
    qpainter qfontmetrics qtextdocument line spacing
    1
    1
    1541
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • P
      Pippin last edited by Pippin

      Hello,

      I am currently working on a project where I have to draw a text inside a rectangle (it's always the same rectangle at the same place on the same image), however the text varies. Sometimes it's a small text and it can be stored in it without adjusting the font size, and sometimes it goes out of the rectangle, and the size has to be decreased until it doesn't go out anymore. (DrawingTool is a QPainter, QLore is a QString, and LORE_FONT is a QFont.)

      	qreal size = 14.;
      	LORE_FONT.setPointSizeF(size);
      	QFontMetrics LoreMetrics(LORE_FONT);
      	QRect foo = LoreMetrics.boundingRect(34, 475, 350, 75, Qt::AlignJustify | Qt::TextWordWrap, QLore);
      	
      	while (foo.height() > 75)
      	{
      		size -= .02;
      		LORE_FONT.setPointSizeF(size);
      		QFontMetrics LoreMetrics(LORE_FONT);
      		foo = LoreMetrics.boundingRect(34, 475, 350, 75, Qt::AlignJustify | Qt::TextWordWrap, QLore);
      	}
      	
      	DrawingTool.setFont(LORE_FONT);
      	DrawingTool.drawText(QRectF(34, 475, 350, 75), QLore);
      

      I wrote this code and it works, any text is always inside the box. My problem is that the spacing between (wrapped) lines isn't high enough and it is a bit hard to read the text. I wanted to fix this and, since I didn't find any way to change that with QPainters, I read about QTextDocuments, but I'm not sure at all how this would play out.

      Is there an easy way to fix my problem?
      If not, do QTextDocument::rootFrame() and QFontMetrics::boundingRect(...) represent the same thing?
      Qt::AlignJustify seems to have no effect on my computer, anybody else using Ubuntu have the same bug?

      1 Reply Last reply Reply Quote 0
      • First post
        Last post