Whether you are building an application or a game using Qt for desktop or mobile, you probably like to see the same fonts on the target computers or phones that you set during development. Well sometimes the fonts that you have used just don’t exist in target platforms. Follow these simple steps to embed a font in your application and guarantee that it will exactly look the same when your users run them.
First of all you have to add a Qt resource file to your project. To do this in Qt Creator right click on your project and click Add New, then select Qt / Qt Resource File (*.qrc file) and give it any names you want.
Next you have to add the font file to your Resource (qrc) file. You can do this by right clicking the resource file that you created and then select open in editor. Now click Add, and then Add Prefix. Name it however you’d like and then Click Add and Add Files so that you can select the font file that you want to embed in your project. (Make sure the font file is in the project folder)
As it is seen in the picture, I created a resource file named “resources.qrc”, and added a prefix named “fonts” and then added the font file named “komika_font.ttf”. Obviously you have to use names that fit your case.
Now to make sure that the font you need (and added to qrc file) exists on the target system, you have to call it using the code below:
Note that you have to replace “:/fonts/komika_font.ttf” with whatever font you want to include in your application.
Now you can set this font using a QFont variable to any widget that supports fonts. Just load the font, in my case it would be something like this: (The font that I embedded in my example app was called Komika Axis, you have to provide the correct font family name here, not the font file name)
QFont font = QFont(“Komika Axis”, 10, 1);
Notice that after calling the above function you can use setFont(font) in most widgets to change the font. (Or using similar methods)
Comment below if you have any questions.