Archived:Calculating text width in Qt
This code snippets shows how to use QFont and QFontMetrics classes to draw string into center of the screen and to get string height and width as pixels.
Note: In order to use this code, you need to have Qt for S60 installed on your platform.
- Install Qt for S60 Garden release from here: Qt for S60 "Garden" pre-release
- Check this link for installation guide: How to install the package
- This source code is use to set the text in center as well as to color the text.
// Create font
// Set current font
// Set font color
// Get QFontMetrics reference
QFontMetrics fm = painter.fontMetrics();
QString text = "helloworld";
// Calculate text center position into the screen using QFontMetrics class
QPoint center = QPoint((widgetSize.width()-fm.width(text))/2,
// QFontMetrics::width() gives calculated text width with current QFont in QPainter
// QFontMetrics::height() gives text height
Text is screen center.