PDA

View Full Version : Text size



bnilsson
2nd October 2008, 21:34
I want to draw a QGraphicsItem rectangle in QGraphicsScene / QGraphicsView framework, and inside the rectangle I want to draw some identifier text which is, say, 50%, of the size of the rectangle itself. I.e. the text size should scale to the rectangle size.

How can I do that?

I tried QFont::setPixelSize(size), but it does NOT work:


void
ChipItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
qreal width, height, size;
QFont monaco("Monaco");
QString pindex;
painter->drawRect(boundingRect());
width = widget->width();
height = widget->height();
if(height>=width) size = width; else size = height;
size /= 2;
monaco.setPixelSize((int)size);
pindex = "P("+pindex.setNum(patindex)+")";
painter->setFont(monaco);
painter->drawText(boundingRect(),Qt::AlignHCenter,pindex);
}


Any suggestions?

caduel
2nd October 2008, 21:45
strange calculation... the pixel size (of the font) is the size of one character (or so), certainly not of the whole text or so.

try something like this


QFont font("monaco");
int pixelSize=20;
while (pixelSize>5 && QFontMetrics(font).boundingRect(yourText).size()>yourItemsSize)
{
--pixelSize;
font.setPixelSize(pixelSize);
}


Untried. Maybe there is a better way to find the maximum font size such that a given text fits a certain rectangle.

HTH

bnilsson
2nd October 2008, 21:56
I'll try it. But it looks like it could add some overhead if I have many rectangles in my picture.


strange calculation... the pixel size (of the font) is the size of one character (or so), certainly not of the whole text or so.
Yes, sorry about being unclear. I meant the text height, primarily. My string would be very short, max 3-4 characters.