How to specify monospace fonts for cross platform Qt applications?

QtFonts

Qt Problem Overview


Is there a platform independent way to specify a fixed width font for a Qt widget ?

If I set the font to "Monospace" in Designer on Linux, it is not found on Windows and Arial is used instead.

Qt Solutions


Solution 1 - Qt

You can use the style hint property of QFont:

QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);

If the font cannot be found (which happens with Monospace on Windows), Qt's font matching algorithm tries to find a font that matches the given style hint.

Solution 2 - Qt

You can retrieve the system's default fixed font using QFontDatabase's systemFont(..) function. It was introduced in Qt 5.2.

Example:

const QFont fixedFont = QFontDatabase::systemFont(QFontDatabase::FixedFont)

Solution 3 - Qt

For all widgets that accept Rich Text you can simply put it into a pre block, i.e. <pre>This is my Text</pre>. It will then use the systems monospace font.

Solution 4 - Qt

I use Courier in Qt on both Linux and Windows.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLuper RouchView Question on Stackoverflow
Solution 1 - QtTorsten MarekView Answer on Stackoverflow
Solution 2 - Qtf15hView Answer on Stackoverflow
Solution 3 - QtbluebrotherView Answer on Stackoverflow
Solution 4 - Qtuser179232View Answer on Stackoverflow