Namespaces
Variants
Actions
Revision as of 11:25, 26 March 2009 by tepaa (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Archived:Calculating text width in Qt

Jump to: navigation, search
Article Metadata

Tested with
Devices(s): 5800 XpressMusic

Compatibility
Platform(s): Qt

Article
Keywords: QFontMetrics, QFont
Created: (26 Mar 2009)
Last edited: tepaa (26 Mar 2009)

Contents

Overview

This code snippets shows how to use QFont and QFontMetrics classes to draw string into center of the screen.

Note: In order to use this code, you need to have Qt for S60 installed on your platform.


Preconditions


Source

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.

531 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved