目录
[qt 加载字体 c++](#qt 加载字体 c++)
qt 加载字体 c++
cpp
#include <QApplication>
#include <QLabel>
#include <QFontDatabase>
#include <QVBoxLayout>
#include <QWidget>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
// 加载字体文件
int fontId = QFontDatabase::addApplicationFont(":/path/to/hyyj.ttf");
if (fontId == -1) {
qWarning() << "Failed to load font!";
return -1;
}
// 获取字体系列名称
QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);
if (fontFamilies.isEmpty()) {
qWarning() << "Failed to retrieve font families!";
return -1;
}
QString fontFamily = fontFamilies.at(0);
// 创建并设置 QLabel
QLabel label("Hello, Qt with custom font!");
QFont customFont(fontFamily);
label.setFont(customFont);
// 设置布局
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(&label);
QWidget window;
window.setLayout(layout);
window.show();
return app.exec();
}
label设置大小和字体:
cpp
auto labelDetails = new QLabel(QString("1235"));
int fontId = QFontDatabase::addApplicationFont("B:/project/mengzong/jianluji/0525/demo/hyyj.ttf");
if (fontId == -1) {
qWarning() << "Failed to load font!";
return ;
}
// 获取字体系列名称
QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);
if (fontFamilies.isEmpty()) {
qWarning() << "Failed to retrieve font families!";
return ;
}
QString fontFamily = fontFamilies.at(0);
QFont customFont(fontFamily);
customFont.setPointSize(48); // 设置字体大小
labelDetails->setFont(customFont);
labelDetails->setAutoFillBackground(true);
labelDetails->setStyleSheet("QLabel { color : rgb(39, 255, 167); }");
labelDetails->setFixedSize(300, 60);
vbox->addWidget(labelDetails);
资源配置路径失败
cpp
int fontId = QFontDatabase::addApplicationFont(":/res/raw/hyyj.ttf");
解决方法:exe相对目录:
cpp
int fontId = QFontDatabase::addApplicationFont("./hyyj.ttf");
pro配置:
bash
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = FontExample
TEMPLATE = app
# 添加字体文件到资源
RESOURCES += resources.qrc
resource.qrc
bash
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>hyyj.ttf</file>
</qresource>
</RCC>