FontLoader. How it work?



  • I have custom font
    I load this font in FontLoader (for example in MyForm.qml)
    I create new QML document and use my custom font . (MySecondForm.qml)

    If I load my font in MyForm.qml his available using in MySecondForm?
    FontLoader loaded font in global environment?



  • You can use a singleton to make it available globally.



  • In your cpp file before loading the QML entry file you can just call QFontDatabase and add it. I'm going to assume the font isn't being downloaded from the internet (using a URL in the FontLoader)

    #include <QFontDatabase>
    ....
    QFontDatabase fontDB;
    fontDb.addApplicationFont("://res/fonts/mycustomfont.otf");
    
    // load QML main file
    // now you can just call the font globally on any QML file. 
    Text {
    font.family: "Source Sans Pro" 
    text: "Hello world"
    }
    

    That's how I've done it, it's been working pretty well.



  • I like the global singleton approach, too. An example would be:

    In a directory called "fonts", Fonts.qml:

    pragma Singleton
    
           import QtQuick 2.5
    
    QtObject {
    
        property FontLoader applicationFont: FontLoader {
            source: "OpenSans-Regular.ttf"
        }
    

    In a qmldir file in the "fonts" folder:

    singleton Fonts Fonts.qml
    

    Then, in your QML files you can use it as follows:

    import "fonts"
    
    Label {
        ...
        font.family:  Fonts.applicationFont.name;
        ...
    }
    


  • @David.G thank you. Your suggested solution is great. someone has another trick like solution here .



  • FontLoader just calls QGuiApplication:: addApplicationFont, it's basically the same as doing it in C++.

    You can use it in another QML file if you know the family name of the font.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.