Namespaces
Variants
Actions
Revision as of 04:17, 11 October 2012 by hamishwillee (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

Jump to: navigation, search
Article Metadata

Tested with
Devices(s): Emulator / desktop / device

Compatibility
Platform(s): All Qt Supported

Article
Keywords: QWidget, QFont, QFontMetrics
Created: Avis (30 Nov 2010)
Last edited: hamishwillee (11 Oct 2012)


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 Archived: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)

165 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