×
Namespaces

Variants
Actions
(Difference between revisions)

How to get maximum Font Size in Qt to fit text into Widget

From Nokia Developer Wiki
Jump to: navigation, search
hamishwillee (Talk | contribs)
m (Tidy up Abstract)
hamishwillee (Talk | contribs)
m (Hamishwillee - Bot change of template (Template:CodeSnippet) - now using Template:ArticleMetaData)
Line 1: Line 1:
 
[[Category:Qt]][[Category:UI]]
 
[[Category:Qt]][[Category:UI]]
{{CodeSnippet
+
{{ArticleMetaData
 
|id=
 
|id=
 
|platform= All Qt Supported  
 
|platform= All Qt Supported  
Line 8: Line 8:
 
|creationdate=30 November 2010
 
|creationdate=30 November 2010
 
|keywords= QWidget, QFont, QFontMetrics
 
|keywords= QWidget, QFont, QFontMetrics
 +
 +
|sourcecode= <!-- Link to example source code (e.g. [[Media:The Code Example ZIP.zip]]) -->
 +
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 +
|sdk=<!-- SDK(s) built and tested against (e.g. [http://linktosdkdownload/ Nokia Qt SDK 1.1]) -->
 +
|devicecompatability=<!-- Compatible devices (e.g.: All* (must have GPS) ) -->
 +
|signing=<!-- Empty or one of Self-Signed, DevCert, Manufacturer -->
 +
|capabilities=<!-- Capabilities required (e.g. Location, NetworkServices.) -->
 +
|author=[[User:Avis]]
 
}}
 
}}
  

Revision as of 12:26, 24 June 2011

Article Metadata
Tested with
Devices(s): Emulator / desktop / device
Compatibility
Platform(s): All Qt Supported
Symbian
Article
Keywords: QWidget, QFont, QFontMetrics
Created: Avis (30 Nov 2010)
Last edited: hamishwillee (24 Jun 2011)


Basic Idea

This article shows how you can calculate the maximum font size of text in a QWidget using the font attributes QFont and QFontMetrics. See also CS001349 - Calculating text width in Qt


And here is contrary task: set font size to maximally fit into widget's size. Simple loop will help.

// Function gets aFont with initialized Font Family, and aText - which size is calculated
void TextWidget::calcFontSize(const QString aText, QFont& aFont)
{
// get widget's width
int wd_width = size().width();
// get widget's height
int wd_hgt = size().height();
int fontPointSize;
// calculating loop
for (int i = 0; i < 200; i++)
{
aFont.setPointSize(i);
// create FontMetrics for resized font
QFontMetrics fm(aFont);
// get text width for current font size
int x = fm.width(aText);
// get text height for current font size
int y = fm.height();
// check if text fits widget
if ((x > wd_width) || (y > wd_hgt))
{
// saving maximum possible size of font
fontPointSize = i-1;
break;
}
}
aFont.setPointSize(fontPointSize);
// as a result - we get already resized aFont
}

--Avis 8:29, 30 November 2010 (UTC)

114 page views in the last 30 days.
×