PDA

View Full Version : Center text on painter



masoroso
2nd May 2006, 12:29
Hi All,

How can I center text at a given x position on a painter?

I use a function to draw lines and above the line I want to set the value of the line (like 0, 2, 4, 6 etc) How can I center these values? I now use something like p.drawText(x,y,`bla') but there must be a way to find out how large 'bla' will be in pixels?

Thanks in advance
Rob

munna
2nd May 2006, 12:36
Use QFontMetrics to find the height, width, ascent and descent of the text you use.

jacek
2nd May 2006, 12:36
I now use something like p.drawText(x,y,`bla') but there must be a way to find out how large 'bla' will be in pixels?
Either use QPainter::boundingRect() or paint the text using different QPainter::drawText() method (the one which takes QRect as the first parameter).

masoroso
2nd May 2006, 14:07
thanks!

I now use


QFontMetrics fm(painter.font());
...
tw = fm.width(sx);
painter.drawText(x+tw/2, y, sx);

btw. I did not understand the boundingRect option... I still need to know the rect dimensions before I call `boundingrect'??

Anyway, it works this way so thank you both,
Rob

masoroso
2nd May 2006, 14:27
whoops sorry..

boundingrect is a better option in this case because QFontMetrics does not have a height() option (and I also need to align to the center of the height).

The code is now rewritten to


QFontMetrics fm(painter.font());
..
xoffset = fm.boundingRect(sx).width()/2;
painter.drawText(x - xoffset, y, sx);

jacek
2nd May 2006, 14:27
I still need to know the rect dimensions before I call `boundingrect'??
No, you don't have to:
If the text does not fit within the given rectangle using the specified flags, the function returns the required rectangle.