×
Namespaces

Variants
Actions
(Difference between revisions)

Archived:Calculating text width in Qt

From Nokia Developer Wiki
Jump to: navigation, search
tepaa (Talk | contribs)
seppo_fn (Talk | contribs)
m (Protected "Calculating text width" [edit=sysop:move=sysop])

Revision as of 12:58, 28 April 2009

Article Metadata
Tested with
Devices(s): 5800 XpressMusic
Compatibility
Platform(s): Qt
Symbian
Article
Keywords: QFontMetrics, QFont
Created: (26 Mar 2009)
Last edited: seppo_fn (28 Apr 2009)

Contents

Overview

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.


Preconditions

Source code

  • This source code is use to set the text in center as well as to color the text.
void QMyWidget::paintEvent(QPaintEvent*)
{
QPainter painter(this);
 
// Create font
QFont f("Helvetica",6);
// 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((widgetSize.width()-fm.width(text))/2,
fm.height());
 
// QFontMetrics::width() gives calculated text width with current QFont in QPainter
// QFontMetrics::height() gives text height
 
painter.drawText(center,text);
}


Postconditions

Text is screen center.

312 page views in the last 30 days.
×