Using custom fonts in Qt

To give a touch of distinction to our applications can happen to use fonts that are not standard, or that are only included with installations of certain programs that we cannot assume are always present (such as MS Office, suites from Adobe…).

The most convenient option is to include them with our application (I will not talk about licenses or anything similar, I assume that everything is in order). For this they can be copied together with the executable, or included in a resource file (QRC). In either case, the sources must be registered before they can be used, especially if we want to use them from style sheets.

// For a font embedded in the resource file
QFontDatabase::addApplicationFont(":/fonts/arialn.ttf");

// In the case it is distributed as a separate file
QFontDatabase::addApplicationFont("../resources/fonts/arialnb.ttf");

Remember that in Qt the paths that begin with : belong to the virtual resource file system, but we’ll talk more about that later. On the other hand, if the fonts are in a directory that is distributed with the application, we can use QApplication::applicationDirPath to ensure that the path we set is not modified by the current working directory:

const auto fonts_dir = qApp->applicationDirPath() + "/../resources/fonts/";
QFontDatabase::addApplicationFont(fonts_dir + "arialnb.ttf");

We can do this in our main() function, just after instantiating the application (QApplication), for example. From that moment on we can use the sources by name as if it were another source of the system.

The counterpart of this is that we must keep this list of fonts updated with those included in the resources, and it may well be that this list is modified by another person on the team (for example, designers), which would imply constant communication with the developer manager so the application loads all resources correctly. With the following code snippet we can load all the fonts contained within a given directory in a full automatic way:

// Substitue ":/fonts/" with the corresponding directory
QDirIterator fonts_it(":/fonts/", QDir::Files);
while (fonts_it.hasNext()) {
 QFontDatabase::addApplicationFont(fonts_it.next());
}