Adding FontAwesome to a Qt/QML Application in 3 Lines

FontAwesome

When writing Qt/QML applications, FontAwesome is frequently handy. Adding it to a Qt/QML app is not different from adding it to apps written with other technologies. You’ll need to download the font files, place those in your project, add the files to a Qt resource file, loading each file into the app font database and then properly use it in QML. This is simple, but these are too many steps for a pretty common operation.

There are other projects the do this, but I did not find one working as I wanted. So I thought I could add FontAwesome support to my project lqtutils, which includes the must-have tools for any typical Qt/QML app I write.

Including FontAwesome in a Project

I typically include lqtutils in every Qt apps I write. If you are not using it, you can include it right away. The FontAwesome part only supports cmake, so you can include lqtutils in your project like this:

include(${CMAKE_CURRENT_SOURCE_DIR}/lqtutils/CMakeLists.txt)

(change the path to whatever you like).

By default, lqtutils won’t add FontAwesome to your project, as the fonts are pretty large and you may not want it. To include FontAwesome, replace the previous line with:

set(ENABLE_FONT_AWESOME true)
include(${CMAKE_CURRENT_SOURCE_DIR}/lqtutils/CMakeLists.txt)

Now you only need to init with this line in your main:

lqt::embed_font_awesome(view.engine()->rootContext());

This will load fonts and register a few components. FontAwesome is now embedded in your application.

Using FontAwesome

The init function loads three font files and registers a few elements in the QML engine. What you’ll probably want to use is:

import "qrc:/lqtutils/fontawesome"

[…]

LQTFontAwesomeFreeSolid {
    width: 16
    height: 16
    iconUtf8: "\uf013"
    iconColor: "orange"
}

The available types are: LQTFontAwesomeFreeSolid, LQTFontAwesomeFreeRegular and LQTFontAwesomeBrandsRegular. The available properties of these elements are:

// Color of the icon
property alias iconColor: innerText.color
// Utf8 character to render
property alias iconUtf8: innerText.text
// The QML Text element inside the component, to have more configuration options
property alias innerTextElement: innerText

The init function also registers the QFont’s inside the QML engine, you may need to use those in other contexts: fontAwesomeBrandsRegular, fontAwesomeFreeRegular and fontAwesomeFreeSolid.

Have fun! 😉

Leave a Reply

Your email address will not be published. Required fields are marked *