Archived:Calculating text width in Qt
This code snippets shows how to use the QFont and QFontMetrics classes to draw a string into the center of the screen and to get the string height and width in pixels.
Note: In order to use this code, you need to have Qt for S60 installed on your platform.
- Install the Qt for S60 Garden release from here: Qt for S60 "Garden" pre-release
- Check the installation guide: How to install the package
- This source code centers the text and sets the text colour.
// 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
The text is centered on the screen.