73

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.

Luper Rouch
  • 9,304
  • 7
  • 42
  • 56

4 Answers4

60

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.

mavroprovato
  • 8,023
  • 5
  • 37
  • 52
Torsten Marek
  • 83,780
  • 21
  • 91
  • 98
  • 4
    Out of curiosity: why not `QFont::Monospace` ? – kralyk Sep 30 '13 at 23:18
  • 7
    A helpful addendum: that code only works if you pass a family name to the QFont constructor. Otherwise, it will use the default font family, which will be variable width, which then overrides the style hint. I had to do this, `QFont font("");`, when I didn't have a specific monospace font to request. – Harvey Oct 15 '13 at 04:46
  • @kralyk I was curious, too, and I tried on Windows and I noticed that `QFont::Monospace` will not result in a monospace font, while `TypeWriter` will. Can't really explain why, though :( – AkiRoss Jun 23 '14 at 12:34
  • (Note, the following is valid for PyQt, I cannot test it for C++ but it should work in the same way) In order to get a font that is proportional to the default one, it's better to use the application font and then set the font family string: `font = QFont()` `font.setFamily('monospace')`; it may still be necessary to set the style hint before the family. – musicamante Oct 09 '21 at 20:01
46

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)
f15h
  • 776
  • 8
  • 5
20

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.

bluebrother
  • 8,636
  • 1
  • 20
  • 21
  • 3
    I tried this in my program and it worked, but it also added a line break following the pre tag. I didn't know how to get rid of that so I tried text instead and that worked! I haven't verified, though, that my solution is portable. – mjwach Apr 25 '16 at 02:22
  • Or `` if you want the text to wrap. – Jonas Eberle Feb 18 '22 at 11:06
7

I use Courier in Qt on both Linux and Windows.