Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed a custom font in my application

Tags:

c++

qt

qt5

I want to add a custom font to my application, and I have already added to my resource file.

And my code as the following:

int id = QFontDatabase::addApplicationFont(":/fonts/ae_AlMateen.ttf");
QMessageBox::information(this,"Message",QString::number(id));

Also the content of .qrc file.

<RCC>
    <qresource prefix="/fonts">
        <file alias="ae_AlMateen">ae_AlMateen.ttf</file>
    </qresource>
</RCC>

But the problem is that the addApplicationFont always returns -1.

Note that when change the :/fonts/ae_AlMateen.ttf to direct path ex:C://ae_AlMateen.ttf it works fine.

I want the font file to be integrated with my application executable file, in order to make the application does not need to attach the font file with it.

like image 678
Lion King Avatar asked May 07 '15 21:05

Lion King


2 Answers

Ahhh... now, after you added your .qrc, I understand. Easy to explain:

<file alias="ae_AlMateen">ae_AlMateen.ttf</file>

You added an alias in your .qrc file. If you remove alias="ae_AlMateen" it will work as we all expected... with .ttf extension.

like image 180
Greenflow Avatar answered Sep 28 '22 06:09

Greenflow


If you are using qml also, you can load font in qml file in this way. I recommend it.

And if you still want to load font from cpp file, please read this article, it may help you.

Edit: The following code can work on Qt5.4.1 on OSX10.10. (The font is embedded in executable file)

int id = QFontDatabase::addApplicationFont(":/fonts/fontawesome-webfont.ttf");
QMessageBox::information(NULL,"Message",QString::number(id));  // this shows id is 0.

QFont font;
font.setFamily("FontAwesome");
font.setPointSize(30);
ui->commandLinkButton->setFont(font);
ui->commandLinkButton->setText("\uf021"); // this shows the Refresh icon.

Edit2: I made another test on Win7 with Qt5.4.1(msvc2013 64bit). The font is embedded in the exe file. Everything works fine.

like image 26
douyw Avatar answered Sep 28 '22 05:09

douyw