×
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
somnathbanik (Talk | contribs)
hamishwillee (Talk | contribs)
m (Tidy up Abstract)
Line 1: Line 1:
[[Category:Qt]]
+
[[Category:Qt]][[Category:UI]]
 
{{CodeSnippet
 
{{CodeSnippet
 
|id=
 
|id=
Line 5: Line 5:
 
|devices= Emulator / desktop / device
 
|devices= Emulator / desktop / device
 
|category=Qt
 
|category=Qt
|subcategory=Qt Gui
+
|subcategory=UI
 
|creationdate=30 November 2010
 
|creationdate=30 November 2010
 
|keywords= QWidget, QFont, QFontMetrics
 
|keywords= QWidget, QFont, QFontMetrics
Line 13: Line 13:
 
== Basic Idea ==
 
== Basic Idea ==
  
 +
{{Abstract|visible=true|This article shows how you can calculate the maximum font size of text in a {{Qapiname|QWidget}} using the font attributes {{Qapiname|QFont}} and {{Qapiname|QFontMetrics}}. See also [[CS001349 - Calculating text width in Qt]] }}
  
{{Abstract|visible=true|We can simply get text size  when we know Font attributes - just use the {{Icode|QFont}} and {{Icode|QFontMetrics}} (to get accurate measures of the text) 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.
 
+
And here is contrary task: set Font Size to maximally fit into widget's size. Simple loop will help.
+
  
 
<code cpp>
 
<code cpp>

Revision as of 02:38, 29 April 2011

Article Metadata
Tested with
Devices(s): Emulator / desktop / device
Compatibility
Platform(s): All Qt Supported
Symbian
Article
Keywords: QWidget, QFont, QFontMetrics
Created: (30 Nov 2010)
Last edited: hamishwillee (29 Apr 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)

112 page views in the last 30 days.
×