Archived:Calculating text width in Qt
S60 5th Edition
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 Symbian installed on your platform.
- Install latest Qt for Symbian see Qt for Symbian - Installation packages
- Check this link for installation guide: How to install the package.
- Go through this article: Getting started with Qt for Symbian
- 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( ( width()-fm.width(text))/2,
( height() - fm.height())/2 );
// QFontMetrics::width() gives calculated text width with current QFont in QPainter
// QFontMetrics::height() gives text height
The text is centered on the screen.
The code example can be found at File:HelloworldNew.zip