c++qtfonts

QFontDatabase doesn't contain all the fonts families or it has different names


I'm getting a QWidget's default font's family using font().family(). I compare this against the QStringList I get from QFontDatabase().families(). The default font's family is "Sans" but I cannot find that in the list I get from QFontDatabase, I can only find Sans Serif, Droid Sans, FreeSans etc. How come QWidget's default font is something that is not even present on the system's fonts?


Solution

  • This is a classic trip-up.

    QFont is a request for a font. It may be satisfied by something that doesn't quite match what was requested. The actual font is available from QFontInfo.

    If you think about it, you can put "whatever" in a QFont. At what point should QFont change itself to indicate what font was actually selected? It'd be rather baffling if you set a font on a widget, then read it back, and it got changed to match what fonts are there. So, there's no such reasonable point where a QFont could morph, so QFont can't be but a request.

    You control QFont, but the system's font availability and other constraints controls the matching QFontInfo.

    The invariant may be expressed as:

    QFontDatabase db;
    QFont const font = widget->font();
    QStringList const families = db.families();
    Q_ASSERT(families.contains(font.family()) || true);
    QFontInfo const info(font);
    Q_ASSERT(families.contains(info.family()));
    

    In win32 GDI parlance, QFont would be called the logical font, and QFontInfo would be called the physical font.