PDA

View Full Version : adjust Font size to a given rect when drawText



yartov
29th April 2008, 19:22
I have to adjust a Font size, when the user resized Widget where I draw text in a given rectangle.
Can somebody to give me a hint or point me to the right example?
Thanks in advance

adonel
2nd May 2008, 00:57
Hi,
You should use the QFontMetrics class. This class has the boundingRect(QString text) method which is exactly what you want.

The idea is to start with a initial font size (e.g. 12) and recusively check if your text can
be drawn in your rect. If no, then you decrease the font size and check again!

Panos

Micawber
2nd May 2008, 18:05
You could also do something like this...



QFont serifont( "Times" );
qreal size1_x, size2_x, size1_y, size2_y;
QMatrix xform = painter.combinedMatrix();
QMatrix invertedxform = xform.inverted();

// calculate and set pixel height for font to be 3% of the display area size
invertedxform.map( qreal( width() * 0.10 ), qreal( height() * 0.10 ), &size1_x, &size1_y );
invertedxform.map( qreal( width() * 0.13 ), qreal( height() * 0.13 ), &size2_x, &size2_y );
serifFont.setPixelSize( static_cast< int >( qAbs( size2_x - size1_x ) ) );
painter.setFont( serifFont );


This will ensure that the font size will stay the same if you scale the coordinates of the widget. I'm sure there's a more elegant way to accomplish it though.

patrik08
12th May 2008, 12:51
I have to adjust a Font size, when the user resized Widget where I draw text in a given rectangle.
Can somebody to give me a hint or point me to the right example?
Thanks in advance

You can draw a arial 6point to a 2000 pixel QWidget and is not need to change point size
only think Vector ...

QPainterPath is your friend ...





void ButtonAction::paintText()
{
QPainter *p = new QPainter(this);
p->setRenderHint(QPainter::Antialiasing);
const int borderI = 25;
/* button text */
QPainterPath textPath;
textPath.addText(borderI,borderI * 2,fontText,textBut); //// fontText is any font() //// textBut text one line
/* fix view from text */
const QRectF reo = textPath.boundingRect();
TXTrect = reo;
/* tanslate text rect to rect window button */
p->setWindow ( reo.x() , reo.y() , reo.width() , reo.height() );
/* color text */
p->setPen(Qt::NoPen);
p->setBrush(colText);
p->drawPath(textPath);
Pm = p->deviceMatrix();
p->end();
}

wysota
12th May 2008, 12:58
I have to adjust a Font size, when the user resized Widget where I draw text in a given rectangle.
Can somebody to give me a hint or point me to the right example?

You can use QPainter::setWindow() and QPainter::setViewport() to modify the "scale" of the painter itself. Then you can use the same font size regardless of the real widget size, because you'll be drawing in logical and not physical coordinates.

yartov
14th May 2008, 20:03
Thanks, I implemented suggestions from other guys, but I want to try your suggestion too. Looks like the right one. Thanks a lot