PDA

View Full Version : Height of the text without balnk space at the top



THRESHE
3rd March 2008, 13:54
Hello everyone
I need to center text in a rectangle and I use QFontMetrics::height() to know the height of it.
But it doesn't return me the height but instead it gives me blank space at the top

QPainter painter(this);
painter.setPen(QPen(QColor(Qt::black)));
QFont font = QFont("Times", 50, QFont::Normal);
painter.setFont(font);
QFontMetrics metrics(font);

int heightOfText = metrics.height();
painter.drawLine(0, 200 - heightOfText,
1000, 200 - heightOfText);
painter.drawLine(0, 200, 1000, 200);
painter.drawText(0, 200, "Gradient Text");

This code gives me the result displayed on the screenshot below :confused:
So My question is how to find text height without that blank space ?
(I suppose it has something with ascent and descent...)

aamer4yu
3rd March 2008, 14:30
or something with lineSpacing() ?? am not sure...

by the way in which case u need to draw lines for text ?? just curious abt what u implemented

THRESHE
3rd March 2008, 14:39
Lines are just for debugging :) And I've tried line spacing but it didn't help :(

aamer4yu
3rd March 2008, 14:49
Just for debugging ??
will this string wont help in this case ??
str = "-------------------------------------------------------------";

why do u need such complex code that lines shud be just touching text ??
wont printing the above simple string solve the purpose ??

wysota
4th March 2008, 17:16
Use QFontMetrics::boundingRect().

THRESHE
4th March 2008, 17:59
Tried that already it didn't work.

Closest to the height of the text is


QFont font = QFont("Trebushet MS", 50, QFont::Normal);
QFontMetrics metrics(font);

int height = metrics.ascent() - metrics.descent() + metrics.leading();

Lykurg
19th March 2008, 13:33
Hi,

the space on top is what is needed for letters like "gjqy" under the baseline. By drawing the Text
painter.drawText(0, 200, "Gradient Text"); you set the baseline at 200. To get the Text vertical centered use
painter.drawText(0, 200+(metrics.boundingRect("m").y()/2), "Gradient Text"); if you have no "gy..." or use
void QPainter::drawText ( int x, int y, int width, int height, int flags, const QString & text, QRect * boundingRect = 0 ) with Qt::AlignHCenter.


Lykurg