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
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
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
You could also do something like this...
Qt Code:
qreal size1_x, size2_x, size1_y, size2_y; // 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 );To copy to clipboard, switch view to plain text mode
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.
yartov (14th May 2008)
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 ...
Qt Code:
void ButtonAction::paintText() { 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 */ 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(); }To copy to clipboard, switch view to plain text mode
yartov (14th May 2008)
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.
Thanks, I implemented suggestions from other guys, but I want to try your suggestion too. Looks like the right one. Thanks a lot
Bookmarks