首页 > 解决方案 > Qml FontLoader 未加载自定义字体

问题描述

我正在尝试使用 Google 字体Inter Regular TTF(我也测试了其他一些字体文件)但 FontLoader 没有加载字体,下面是我的代码。

我已将字体文件复制到.ttf资源.qrc“字体”文件夹中。
我已经定义了一个通用样式文件并加载了在整个应用程序中使用的字体。

// ------- Style.qml --------
pragma Singleton
import QtQuick 2.12

QtObject {

    property var myFontInterRegular: FontLoader {
        source: "qrc:/fonts/Inter-Regular.ttf"
        onStatusChanged: {
            console.log("onStatusChanged status:"+status); // Not getting called
        }
    }
}

信号onStatusChanged没有被调用,所以我认为我的字体没有加载。
我使用的字体如下:

// ------- TestPage.qml --------
import QtQuick 2.12
import "."

Rectangle {
    id: parentRect
    width: parent.width
    height: parent.height

    Text {
        id: myTxt
        text: "Hello In Inter-Regular"
        font.family: Style.myFontInterRegular.name // Getting error "name" not defined
    }
}

当我运行代码时出现错误:
TypeError: Cannot read property 'name' of undefined对于该行Style.myFontInterRegular.name

标签: qtfontsqmlqt5qtquick2

解决方案


我用过的和工作的:

// ------assets/Style.qml---------
pragma Singleton

Item {
    property alias fontAwesome: fontAwesomeLoader.name
    FontLoader {
        id: fontAwesomeLoader
        source: "qrc:/fonts/fontawesome.ttf"
    }
}
// ------- TestPage.qml --------
import QtQuick 2.12
import assets 1.0 // This works using qmldir and assets.qrc

Rectangle {
    id: parentRect
    width: parent.width
    height: parent.height

    Text {
        id: myTxt
        text: "Hello In Inter-Regular"
        font.family: Style.fontAwesome
    }
}
// ---assets.qrc----
<RCC>
    <qresource prefix="/assets">
         <file alias="qmldir">assets/qmldir</file>
         <file alias="Style.qml">assets/Style.qml</file>
    </qresource>
</RCC>
// ---assets/qmldir----
module assets
singleton Style 1.0 Style.qml

推荐阅读