(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 (Added category Category:Maemo. (Adding Maemo to all Qt for Maemo topics in preparation for ontology change))
hamishwillee (Talk | contribs)
m (Remove platform specifier categories (only need specifier for Qt if there is some platform specific behaviour))
Line 1: Line 1:
[[Category:Qt]][[Category:Qt for Maemo]][[Category:Qt for Symbian]]
Line 47: Line 47:
--[[User:Avis|Avis]] 8:29, 30 November 2010 (UTC) [[Category:Maemo]]
--[[User:Avis|Avis]] 8:29, 30 November 2010 (UTC)

Revision as of 03:59, 1 April 2011

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

We can simply get text size when we know Font attributes - just use the QFont and QFontMetrics like in this article 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++)
// 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;
// as a result - we get already resized aFont

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

149 page views in the last 30 days.