2015-06-22 64 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" }