QFontDatabase doesn't contain all the fonts fa

2019-05-17 16:18发布

问题:

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?

回答1:

This is a classic trip-up.

Logically, 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()));


回答2:

Sans is a family alias.

Droid Sans is a font family name.

QFont("Sans") returns a font with family "Sans" and closest params for your request (.boldness, size, lang, script, features, etc)



标签: c++ qt fonts