PDA

View Full Version : Length of text in QFontMetrics



Screamer2087
6th January 2014, 16:28
Hello,

I'm trying to draw a rect around a text. I have the problem, that the rect is much too small in comparison to my text. I'm trying to get the length of the text with QFontMetrics. Here is a small example:



QPainter p(this);

QFont font;
font.setFamily("Arial");
font.setPixelSize(10);
font.setBold(false);

QFontMetricsF metrics(font);

qreal width = metrics.width("Test");
p.drawRect(0,0,width, 20);
p.drawText(QRect(0,0,width,20),"Test");

qreal width1 = metrics.width("LongTest");
p.drawRect(0,20,width1, 20);
p.drawText(QRect(0,20,width1,20),"LongTest");

qreal width2 = metrics.width("LongLongTest");
p.drawRect(0,40,width2, 20);
p.drawText(QRect(0,40,width2,20),"LongLongTest");


The result in a QWidget you can see here:
9909

I'm using Qt 5 in a Kubuntu 13.04 system. Do I do anything wrong or is it a (huge) bug in Qt? I tested it with different font families and sizes. The result is always the same.

I hope you can help me!

Greetz
Screamer

anda_skoa
7th January 2014, 00:24
You could be using a different font for calculation than for painting.
Either set the font on the painter or use the painter's font/fontmetrics

Cheers,
_