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 latest Qt for S60 see Qt for S60 - Installation packages
- Check this link for installation guide: How to install the package.
- Go through this article: Getting started with Qt for S60
- 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.