Tuesday, January 22, 2013

Cross-Platform Fixed Width Font

There are several solutions for setting the font in the edit box to a fixed width font, but a cross-platform solution was needed.  One solution would be to use a font that is available on both Windows and Linux, for example Courier, but this is not the best looking font, though it is one of the few available on Windows.  My current preferred fixed width font is Monospace, but this font is not available on Windows.  Attempting to set this font had no effect on Windows, and the default proportional font was used.

After some research, the correct sequence was found to select the Monospace font on Linux and to select an alternate fixed width font on Windows.  First the current font is obtained from the QTextEdit base class.  The font is set to fixed pitch to indicate the type of font desired if the selected font family is not found.  The font family is set to the "Monospace" string and the style hint is set to Monospace.  Finally the current font is set to this modified font.  This code was put into the EditBox constructor:
QFont font = currentFont();
font.setFixedPitch(true);
font.setFamily("Monospace");
font.setStyleHint(QFont::Monospace);
setCurrentFont(font);
On Windows (XP, 7 and 8), this appears to select the Courier New font at a fairly small 8 point font, which doesn't look so good on XP, but better on 7 and 8.  The size of the Monospace font on Linux also looks to be an 8 point font.  This is good enough for the now and eventually a font selection dialog will be added so that any font and size can be selected.

[commit 7155b30097]