最近开发项目时,据说不能用系统自带的微软雅黑字体,于是找一个开源的字体,思源黑体,这个是google和Adobe公司合力开发的可以免费使用。本篇记录一下Qt使用第三方字体的方式。字体从下载之家下载http://www.downza.cn/soft/266042.html。下载解压后有8种字体
代码实现
cpp
#include "mainwindow.h"
#include <QFont>
#include <QFontDatabase>
#include <QApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString path = QCoreApplication::applicationDirPath();
int fontIndex = 0;
switch (fontIndex) {
case 0:
path = path + QString("/font/SourceHanSans-Bold.otf");
break;
case 1:
path = path + QString("/font/SourceHanSans-CNBold.ttf");
break;
case 2:
path = path + QString("/font/SourceHanSans-ExtraLight.otf");
break;
case 3:
path = path + QString("/font/SourceHanSans-Heavy.otf");
break;
case 4:
path = path + QString("/font/SourceHanSans-Light.otf");
break;
case 5:
path = path + QString("/font/SourceHanSans-Medium.otf");
break;
case 6:
path = path + QString("/font/SourceHanSans-Normal.ttf");
break;
case 7:
path = path + QString("/font/SourceHanSans-Regular.ttf");
break;
default:
path = path + QString("/font/SourceHanSans-CNBold.ttf");
break;
}
int fontId = QFontDatabase::addApplicationFont(path);
QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);
if (!fontFamilies.empty())
{
QString fontFamily = fontFamilies.at(0);
QFont defaultFont = a.font();
defaultFont.setFamily(fontFamily);
defaultFont.setPixelSize(15);
a.setFont(defaultFont);
}
MainWindow w;
w.show();
return a.exec();
}
运行效果:
第2种字体效果:
第3种字体效果:
第4种字体效果:
第5种字体效果:
第6种字体效果:
第7种字体效果:
第8种字体效果: