×
Namespaces

Variants
Actions
Revision as of 16:41, 28 March 2009 by mind_freak (Talk | contribs)

Archived:Calculating text width in Qt

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Tested with
Devices(s): 5800 XpressMusic
Compatibility
Platform(s): Qt
Symbian
Article
Keywords: QFontMetrics, QFont
Created: (26 Mar 2009)
Last edited: mind_freak (28 Mar 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 the pixel width as height of the string.

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


Preconditions


To find the Font wide and height

Main Function

  • Returns the width in pixels of the first len characters of text.
int pixelsWide = fm.width("What's the width of this text?");
  • Return the height in pixel of the given string.
int pixelsHigh = fm.height();


Source Code

#include <QtGui/QApplication>
#include "lblfont.h"
#include<QWidget>
#include<QFormLayout>
#include<QPainter>
#include<QFont>
#include<QFontMetrics>
#include<QString>
#include<QLabel>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget *win=new QWidget();
QFormLayout *lay=new QFormLayout();
QFont f("Helvetica",6);
QFontMetrics fm(f);
int pixelsWide = fm.width("What's the width of this text?");
int pixelsHigh = fm.height();
QString str;
QString str2;
str=str.number(pixelsWide);
str2=str2.number(pixelsHigh);
QLabel *lbl=new QLabel();
QLabel *lbl1=new QLabel();
QLabel *lbl2=new QLabel("Text width in Pixels:");
QLabel *lbl3=new QLabel("Text height in Pixels:");
lbl->setText(str);
lbl1->setText(str2);
lay->addRow(lbl2,lbl);
lay->addRow(lbl3,lbl1);
win->setLayout(lay);
win->show();
return a.exec();
}

Screenshot

Fontmetric1111.JPG




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.

291 page views in the last 30 days.