QFont Class

  • Header: QFont

  • CMake:

    find_package(Qt6 REQUIRED COMPONENTS Gui)

    target_link_libraries(mytarget PRIVATE Qt6::Gui)

  • qmake: QT += gui

  • Group: QFont is part of Painting Classes, appearance, shared, Rich Text Processing APIs

Detailed Description

QFont can be regarded as a query for one or more fonts on the system.

When you create a QFont object you specify various attributes that you want the font to have. Qt will use the font with the specified attributes, or if no matching font exists, Qt will use the closest matching installed font. The attributes of the font that is actually used are retrievable from a QFontInfo object. If the window system provides an exact match exactMatch() returns true. Use QFontMetricsF to get measurements, e.g. the pixel length of a string using QFontMetrics::width().

Attributes which are not specifically set will not affect the font selection algorithm, and default values will be preferred instead.

To load a specific physical font, typically represented by a single file, use QRawFont instead.

Note that a QGuiApplication instance must exist before a QFont can be used. You can set the application's default font with QGuiApplication::setFont().

If a chosen font does not include all the characters that need to be displayed, QFont will try to find the characters in the nearest equivalent fonts. When a QPainter draws a character from a font the QFont will report whether or not it has the character; if it does not, QPainter will draw an unfilled square.

Create QFonts like this:

 
Sélectionnez
QFont serifFont("Times", 10, QFont::Bold);
QFont sansFont("Helvetica [Cronyx]", 12);

The attributes set in the constructor can also be set later, e.g. setFamily(), setPointSize(), setPointSizeF(), setWeight() and setItalic(). The remaining attributes must be set after construction, e.g. setBold(), setUnderline(), setOverline(), setStrikeOut() and setFixedPitch(). QFontInfo objects should be created after the font's attributes have been set. A QFontInfo object will not change, even if you change the font's attributes. The corresponding "get" functions, e.g. family(), pointSize(), etc., return the values that were set, even though the values used may differ. The actual values are available from a QFontInfo object.

If the requested font family is unavailable you can influence the font matching algorithm by choosing a particular QFont::StyleHint and QFont::StyleStrategy with setStyleHint(). The default family (corresponding to the current style hint) is returned by defaultFamily().

You can provide substitutions for font family names using insertSubstitution() and insertSubstitutions(). Substitutions can be removed with removeSubstitutions(). Use substitute() to retrieve a family's first substitute, or the family name itself if it has no substitutes. Use substitutes() to retrieve a list of a family's substitutes (which may be empty). After substituting a font, you must trigger the updating of the font by destroying and re-creating all QFont objects.

Every QFont has a key() which you can use, for example, as the key in a cache or dictionary. If you want to store a user's font preferences you could use QSettings, writing the font information with toString() and reading it back with fromString(). The operator<<() and operator>>() functions are also available, but they work on a data stream.

It is possible to set the height of characters shown on the screen to a specified number of pixels with setPixelSize(); however using setPointSize() has a similar effect and provides device independence.

Loading fonts can be expensive, especially on X11. QFont contains extensive optimizations to make the copying of QFont objects fast, and to cache the results of the slow window system functions it depends upon.

The font matching algorithm works as follows:

  1. The specified font families (set by setFamilies()) are searched for.

  2. If not, a replacement font that supports the writing system is selected. The font matching algorithm will try to find the best match for all the properties set in the QFont. How this is done varies from platform to platform.

  3. If no font exists on the system that can support the text, then special "missing character" boxes will be shown in its place.

If the selected font, though supporting the writing system in general, is missing glyphs for one or more specific characters, then Qt will try to find a fallback font for this or these particular characters. This feature can be disabled using QFont::NoFontMerging style strategy.

In Windows a request for the "Courier" font is automatically changed to "Courier New", an improved version of Courier that allows for smooth scaling. The older "Courier" bitmap font can be selected by setting the PreferBitmap style strategy (see setStyleStrategy()).

Once a font is found, the remaining attributes are matched in order of priority:

  1. fixedPitch()

  2. pointSize() (see below)

  3. weight()

  4. style()

If you have a font which matches on family, even if none of the other attributes match, this font will be chosen in preference to a font which doesn't match on family but which does match on the other attributes. This is because font family is the dominant search criteria.

The point size is defined to match if it is within 20% of the requested point size. When several fonts match and are only distinguished by point size, the font with the closest point size to the one requested will be chosen.

The actual family, font size, weight and other font attributes used for drawing text will depend on what's available for the chosen family under the window system. A QFontInfo object can be used to determine the actual values used for drawing the text.

Examples:

 
Sélectionnez
QFont f("Helvetica");

If you had both an Adobe and a Cronyx Helvetica, you might get either.

 
Sélectionnez
QFont f("Helvetica [Cronyx]");

You can specify the foundry you want in the family name. The font f in the above example will be set to "Helvetica [Cronyx]".

To determine the attributes of the font actually used in the window system, use a QFontInfo object, e.g.

 
Sélectionnez
QFontInfo info(f1);
QString family = info.family();

To find out font metrics use a QFontMetrics object, e.g.

 
Sélectionnez
QFontMetrics fm(f1);
int textWidthInPixels = fm.horizontalAdvance("How many pixels wide is this text?");
int textHeightInPixels = fm.height();

For more general information on fonts, see the comp.fonts FAQ. Information on encodings can be found from the UTR17 page.

See Also

Member Type Documentation

 

enum QFont::Capitalization

Rendering option for text this font applies to.

Constant

Value

Description

QFont::MixedCase

0

This is the normal text rendering option where no capitalization change is applied.

QFont::AllUppercase

1

This alters the text to be rendered in all uppercase type.

QFont::AllLowercase

2

This alters the text to be rendered in all lowercase type.

QFont::SmallCaps

3

This alters the text to be rendered in small-caps type.

QFont::Capitalize

4

This alters the text to be rendered with the first character of each word as an uppercase character.

enum QFont::HintingPreference

This enum describes the different levels of hinting that can be applied to glyphs to improve legibility on displays where it might be warranted by the density of pixels.

Constant

Value

Description

QFont::PreferDefaultHinting

0

Use the default hinting level for the target platform.

QFont::PreferNoHinting

1

If possible, render text without hinting the outlines of the glyphs. The text layout will be typographically accurate and scalable, using the same metrics as are used e.g. when printing.

QFont::PreferVerticalHinting

2

If possible, render text with no horizontal hinting, but align glyphs to the pixel grid in the vertical direction. The text will appear crisper on displays where the density is too low to give an accurate rendering of the glyphs. But since the horizontal metrics of the glyphs are unhinted, the text's layout will be scalable to higher density devices (such as printers) without impacting details such as line breaks.

QFont::PreferFullHinting

3

If possible, render text with hinting in both horizontal and vertical directions. The text will be altered to optimize legibility on the target device, but since the metrics will depend on the target size of the text, the positions of glyphs, line breaks, and other typographical detail will not scale, meaning that a text layout may look different on devices with different pixel densities.

Please note that this enum only describes a preference, as the full range of hinting levels are not supported on all of Qt's supported platforms. The following table details the effect of a given hinting preference on a selected set of target platforms.

 

PreferDefaultHinting

PreferNoHinting

PreferVerticalHinting

PreferFullHinting

Windows and DirectWrite enabled in Qt

Full hinting

Vertical hinting

Vertical hinting

Full hinting

FreeType

Operating System setting

No hinting

Vertical hinting (light)

Full hinting

Cocoa on macOS

No hinting

No hinting

No hinting

No hinting

Please be aware that altering the hinting preference on Windows is available through the DirectWrite font engine. This is available on Windows Vista after installing the platform update, and on Windows 7. In order to use this extension, configure Qt using -directwrite. The target application will then depend on the availability of DirectWrite on the target system.

enum QFont::SpacingType

Constant

Value

Description

QFont::PercentageSpacing

0

A value of 100 will keep the spacing unchanged; a value of 200 will enlarge the spacing after a character by the width of the character itself.

QFont::AbsoluteSpacing

1

A positive value increases the letter spacing by the corresponding pixels; a negative value decreases the spacing.

enum QFont::Stretch

Predefined stretch values that follow the CSS naming convention. The higher the value, the more stretched the text is.

Constant

Value

Description

QFont::AnyStretch

0

0 Accept any stretch matched using the other QFont properties (added in Qt 5.8)

QFont::UltraCondensed

50

50

QFont::ExtraCondensed

62

62

QFont::Condensed

75

75

QFont::SemiCondensed

87

87

QFont::Unstretched

100

100

QFont::SemiExpanded

112

112

QFont::Expanded

125

125

QFont::ExtraExpanded

150

150

QFont::UltraExpanded

200

200

See Also

See also setStretch(), stretch()

enum QFont::Style

This enum describes the different styles of glyphs that are used to display text.

Constant

Value

Description

QFont::StyleNormal

0

Normal glyphs used in unstyled text.

QFont::StyleItalic

1

Italic glyphs that are specifically designed for the purpose of representing italicized text.

QFont::StyleOblique

2

Glyphs with an italic appearance that are typically based on the unstyled glyphs, but are not fine-tuned for the purpose of representing italicized text.

See Also

See also Weight

enum QFont::StyleHint

Style hints are used by the font matching algorithm to find an appropriate default family if a selected font family is not available.

Constant

Value

Description

QFont::AnyStyle

5

leaves the font matching algorithm to choose the family. This is the default.

QFont::SansSerif

Helvetica

the font matcher prefer sans serif fonts.

QFont::Helvetica

0

is a synonym for SansSerif.

QFont::Serif

Times

the font matcher prefers serif fonts.

QFont::Times

1

is a synonym for Serif.

QFont::TypeWriter

Courier

the font matcher prefers fixed pitch fonts.

QFont::Courier

2

a synonym for TypeWriter.

QFont::OldEnglish

3

the font matcher prefers decorative fonts.

QFont::Decorative

OldEnglish

is a synonym for OldEnglish.

QFont::Monospace

7

the font matcher prefers fonts that map to the CSS generic font-family 'monospace'.

QFont::Fantasy

8

the font matcher prefers fonts that map to the CSS generic font-family 'fantasy'.

QFont::Cursive

6

the font matcher prefers fonts that map to the CSS generic font-family 'cursive'.

QFont::System

4

the font matcher prefers system fonts.

enum QFont::StyleStrategy

The style strategy tells the font matching algorithm what type of fonts should be used to find an appropriate default family.

The following strategies are available:

Constant

Value

Description

QFont::PreferDefault

0x0001

the default style strategy. It does not prefer any type of font.

QFont::PreferBitmap

0x0002

prefers bitmap fonts (as opposed to outline fonts).

QFont::PreferDevice

0x0004

prefers device fonts.

QFont::PreferOutline

0x0008

prefers outline fonts (as opposed to bitmap fonts).

QFont::ForceOutline

0x0010

forces the use of outline fonts.

QFont::NoAntialias

0x0100

don't antialias the fonts.

QFont::NoSubpixelAntialias

0x0800

avoid subpixel antialiasing on the fonts if possible.

QFont::PreferAntialias

0x0080

antialias if possible.