Search code examples
qttextfontsqmlqt5

Importing a Semibold font to QML


I am trying to import a Semibold font, in particular, the Montserrat Semibold variant to QML. In order to do so, I'm using the following code:

FontLoader{
    id: semi
    source: "Montserrat-SemiBold.ttf"
}

Where Montserrat-SemiBold.ttf is the following file:

enter image description here

And then I try to visualize it on screen with the Text type:

Text{
   text: Math.round(100*progress.value) + "%"
   anchors.horizontalCenter: parent.horizontalCenter
   font.pixelSize: qmlCfg.fontSize
   color: "black"
   font.family: semi.name
   font.bold: true
}

The problem is that the text appears to be bold, and not semibold, as I was expecting:

enter image description here

As you can see, this 35% looks more bold than semibold to me:

enter image description here

Do you know how to fix this? If I set font.bold: false, the text changes to the regular variant, which is not what I want either.


Solution

  • Are you sure that your font is properly loaded? For me this example gives the correct output as shown in the screenshot.

    Besides the font.bold property there is also font.weight on which you can set the weight of semi bold (600), but as you can see in my example it doesn't have an impact on the text as the font only includes one font weight which is semi bold (600). This you can also see in the console output added to the FontLoader.

    Output

    qml: Font weight 600
    

    Example

    import QtQuick
    
    Window {
        title: "Font"
        width: 1000
        height: 240
        visible: true
    
        FontLoader {
            id: webFont
            source: "qrc:/Montserrat-SemiBold.ttf"
    
            Component.onCompleted: console.log("Font weight", webFont.font.weight)
        }
    
        component TestText: Text {
            text: "Whereas recognition of the inherent dignity"
            font.family: webFont.font.family
            font.pixelSize: 48
        }
    
        Column {
            TestText {}
            TestText { font.weight: 600 }
            TestText { font.bold: true }
        }
    }
    

    enter image description here


    .
    ├── assets.qrc
    ├── CMakeLists.txt
    ├── main.cpp
    ├── main.qml
    └── Montserrat-SemiBold.ttf
    

    assets.qrc

    <RCC>
        <qresource prefix="/">
            <file>Montserrat-SemiBold.ttf</file>
        </qresource>
    </RCC>
    

    CMakeLists.txt

    ...
    set(CMAKE_AUTORCC ON)
    
    qt_add_executable(appuntitledStackoverflow
        assets.qrc
        main.cpp
    )
    ...