【问题标题】:Qml FontLoader not loading the custom fontQml FontLoader 未加载自定义字体
【发布时间】:2021-06-16 10:12:43
【问题描述】:

我正在尝试使用 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 for the line Style.myFontInterRegular.name

【问题讨论】:

  • 当我尝试它时它工作。作为健全性检查,请尝试进行清洁然后重建。当我第一次将字体添加到资源文件时,出于某种原因,我不得不这样做。

标签: qt fonts qml qt5 qtquick2


【解决方案1】:

我使用过的和工作过的:

// ------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

【讨论】:

  • 谢谢,我错过了qmldir 文件。根据文档,我们需要将此文件添加到项目的根目录中。
猜你喜欢
  • 2023-04-03
  • 2016-10-29
  • 1970-01-01
  • 2014-12-14
  • 2019-03-30
  • 2016-07-11
  • 1970-01-01
  • 2022-08-20
  • 2013-02-07
相关资源
最近更新 更多