Project

General

Profile

Packing Fonts into QT app executables

With this approach you know that the fonts are 100% guaranteed to be there if the app is there. You don't need to deal with special cases of the font not being found, or differing paths on platforms, or one application overwriting the font your application installed, or having a font installed with the same name but that actually is a slightly different variant that looks different. It is also 100% cross platform and once you build the Qt App it will work the same on Linux and Windows and you don't need to have a "Installing fonts..." step or junk up the user's computer with fonts they probably don't want anywhere else.

Note that it is very important that you only use fonts that are freely licensed! Most commercial fonts from e.g. Adobe, Monotype, etc. require an explicit license for bundling into an app or embedded device, and this is not cheap and often involves a per-unit royalty. In general, get all fonts from Google Web Fonts which are free and permissively licensed.

Put the fonts into a resource file (.qrc)

<RCC>
  <qresource prefix="/">
    <file>fonts/Federation_Wide.ttf</file>
    ...
  </qresource>
</RCC>

Install the fonts with a QT method

QFontDatabase::addApplicationFont(pathToFontQrcFile);
where pathToFontQrcFile might look something like this: ":/fonts"

Example

This is some example code which calls addFontsFromResources() which will automatically scan your resources for a top-level fonts folder, then installs any TTF or OTF font file it finds.

main.cpp

#include "AddFontsFromResources.h" 

int main(int argc, char *argv[])
{
  QStringList addedFonts = addFontsFromResources();
  for ( const QString& font : addedFonts )
  {
    qDebug() << "Added font:" << font;
  }
}

AddFontsFromResources.h

pragma once

#include <QDirIterator>
#include <QStringList>
#include <QFontDatabase>

namespace
{
  QStringList addFontsFromResources(const QStringList& filters={QStringLiteral("*.ttf"),QStringLiteral("*.otf")})
  {
    QStringList addedFonts;
    QDirIterator iter(QStringLiteral(":/fonts"), filters, QDir::Files|QDir::Readable, QDirIterator::Subdirectories);
    while (iter.hasNext())
    {
      const QString& entry = iter.next();
      if ( QFontDatabase::addApplicationFont(entry) >= 0 )
      {
        addedFonts << entry;
      }
    }
    return addedFonts;
  }
}

Go to top
Add picture from clipboard (Maximum size: 1 GB)