qtfontsqml

How to apply a custom font to all elements in QML


I want to know if there is a way to apply a custom font to all elements in QML like we can easily do in HTML, setting the font on the tag body. I already have the font accessible in QML with:

FontLoader { id: robotoRegular; source: "fonts/Roboto-Regular.ttf" }

But now if I do something like:

ApplicationWindow {
    font.family: robotoRegular.name

It doesn't seem to work, and probably isn't supposed to. Or is there a way?

I'm using Qt 5.11.2, QtQuick 2.2.


Solution

  • Try this code:

    #include <QFontDatabase>
    
    void InstallDefaultFont()
    {
        qint32 fontId = QFontDatabase::addApplicationFont(":/font.otf");
        QStringList fontList = QFontDatabase::applicationFontFamilies(fontId);
    
        QString family = fontList.first();
        QGuiApplication::setFont(QFont(family));
    }
    

    This will setup the default font for QML and Widgets as well.