Archived:Calculating text width in Qt
Article Metadata
Tested with
Devices(s): Nokia 5800 XpressMusic
Compatibility
Platform(s): S60 3rd Edition, FP1, FP2
S60 5th Edition
S60 5th Edition
Platform Security
Capabilities: )
Article
Keywords: QFontMetrics, QFont
Created: tepaa
(29 Apr 2009)
Last edited: hamishwillee
(15 Feb 2012)
Contents |
Overview
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.
Preconditions
- Install Nokia Qt SDK
Source code
- This source code centers the text and sets the text colour.
void QMyWidget::paintEvent(QPaintEvent*)
{
QPainter painter(this);
// Create font
QFont f("Helvetica",20);
// Set current font
painter.setFont(f);
// Set font color
painter.setPen(Qt::white);
// 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
painter.drawText(center,text);
}
Postconditions
The text is centered on the screen.
The code example can be found at File:HelloworldNew.zip

