2015-06-22 61 views
10

添加自定义字体添加此字体资源:BYekan.ttf
我想在我的应用程序使用该字体。我试过这个:QT间从资源

QFont font(":/images/font/BYekan.ttf"); 
    nLabel->setFont(font); 
    nLabel->setText(tr("This is for test")); 
    layout->addWidget(nLabel); 

但是,我猜这是行不通的。如何使用它?

编辑: 阅读this question之后,我又试了一次:

int fontID(-1); 
bool fontWarningShown(false); 
QFile res(":/images/font/Yekan.ttf"); 
if (res.open(QIODevice::ReadOnly) == false) { 
    if (fontWarningShown == false) { 
     QMessageBox::warning(0, "Application", (QString)"Impossible d'ouvrir la police " + QChar(0x00AB) + " DejaVu Serif " + QChar(0x00BB) + "."); 
     fontWarningShown = true; 
    } 
}else { 
    fontID = QFontDatabase::addApplicationFontFromData(res.readAll()); 
    if (fontID == -1 && fontWarningShown == false) { 
     QMessageBox::warning(0, "Application", (QString)"Impossible d'ouvrir la police " + QChar(0x00AB) + " DejaVu Serif " + QChar(0x00BB) + "."); 
     fontWarningShown = true; 

    } 
    else 
     nLabel->setFont(QFont(":/images/font/Yekan.ttf", 10)); 
} 

我比较这字体和其他字体,但没有Qt的有什么不同。为什么?

+0

尝试 QFont字体( “:/图像/字体/ BYekan.ttf”); nLabel-> setFont(font); – Ankur

+0

我试过了,但仍然不起作用 – AFN

回答

21
int id = QFontDatabase::addApplicationFont(":/fonts/monospace.ttf"); 
QString family = QFontDatabase::applicationFontFamilies(id).at(0); 
QFont monospace(family); 
+0

如何使用它? nLabel-> setFont(monospace(family)); 错误:不对应的呼叫 '(QFont)(QString的&)' – AFN

+1

没有,像这样。 nLabel-> setFont(monospace); – Ankur

+0

id是-1,如果字体无法加载 – Paglian

1

在QML可以

FontLoader { id: font; source: "/fonts/font.otf" }