4

Qt QML qtquickcontrols2.conf 使用系统未安装的自定义字体

 3 years ago
source link: https://www.mycode.net.cn/language/cpp/2912.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Qt QML qtquickcontrols2.conf 使用系统未安装的自定义字体

现在很多视觉设计最终给出的字体可能并不是所有系统都安装过的,所以项目中可能需要单独把字体文件打包进去在程序运行的时候加载。Qt QML 有多种方式加载一个自定义字体,本文将介绍所有我知道的方式,大家根据自己的需要选择使用任意一种即可。

使用 FontLoader 方式加载并使用

FontLoader 在 QML 文档中有非常详细的介绍,加载和使用字体的方式如下:

import QtQuick 2.0

Column {
    FontLoader { id: fixedFont; name: "Courier" }
    FontLoader { id: webFont; source: "http://www.mysite.com/myfont.ttf" }

    Text { text: "Fixed-size font"; font.family: fixedFont.name }
    Text { text: "Fancy font"; font.family: webFont.name }
}

FontLoader 可以加载网络字体、系统中已经安装的字体和本地文件的字体,当然也可以从资源文件中加载。但是如果你把很大的字体文件放到资源文件中,那么编译出来的执行文件体积也会随之增加,所以不推荐这样尝试。

C++ 加载字体 qtquickcontrols2.conf 配置设置全局字体

Qt Quick 提供了一种通过 qtquickcontrols2.conf 设置全局字体的方式,通过 qtquickcontrols2.conf 设置后你不需要像上面示例代码中给单独的控件设置字体样式。见此文档:https://doc.qt.io/qt-5/qtquickcontrols2-configuration.html。使用 qtquickcontrols2.conf 来加载字体前提是你的应用程序已经加载了字体,我们可以通过 C++ 代码在运行 QML Engine 前将字体加载好:

// Load font from local file
int localFont = QFontDatabase::addApplicationFont(QGuiApplication::applicationDirPath() + "/fonts/PingFang.ttf");
QFontDatabase::applicationFontFamilies(localFont);

这样你将字体文件放到跟你执行程序相同目录下的 fonts 文件夹即可。程序运行会先加载字体,随后 QML 界面弹出发现 qtquickcontrols2.conf 设置了你需要的字体则加载该字体使用。比如我们使用的是 Material 样式,那么我们在 Material 样式下面设置默认字体为我们刚刚加载的 PingFang SC 就可以跑起来了。

[Material]
Primary=#337EFF
Accent=#337EFF
Theme=System
Background=#FFFFFF
Font\Family=PingFang SC
Font\PixelSize=14
本条目发布于2020年2月13日。属于C/C++LanguageQML分类,被贴了 QMLQtQt Quick 标签。 ← 2020 新的开始 Qt Quick Windows 下实现无边框窗口阴影效果 →

发表评论 取消回复

电子邮件地址不会被公开。 必填项已用*标注

评论

姓名 *

电子邮件 *

站点


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK