在 Qt 中全局加载一个 TTF 字体文件并使用它

阅读数:205 评论数:0

跳转到新版页面

分类

C/C++

正文

在 Qt 中全局加载一个 TTF 字体文件并使用它,你可以在程序初始化时期,比如在 main 函数中加载字体。以下是加载全局字体的步骤:

  • 加载字体文件:使用 QFontDatabase::addApplicationFont 方法加载字体文件。
  • 检查加载是否成功:确认字体已经被正确加载。
  • 设置字体:使用加载的字体创建 QFont 对象,并通过 QApplication::setFont 设置为应用程序的默认字体。

下面是一个示例代码:

#include <QApplication>
#include <QFontDatabase>
#include <QWidget>
#include <QLabel>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // 加载字体文件
    int fontId = QFontDatabase::addApplicationFont(":/path/to/yourfont.ttf");
    if (fontId != -1) {
        // 获取字体家族名称
        QStringList fontFamily = QFontDatabase::applicationFontFamilies(fontId);
        if (!fontFamily.empty()) {
            // 设置应用程序全局字体
            QFont appFont(fontFamily.at(0));
            app.setFont(appFont);
        }
    }

    // 创建并显示 QLabel
    QLabel label("This is a label with the globally loaded font");
    label.show();

    return app.exec();
}



相关推荐