Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Font Awesome in QML

Does anyone knows how to use Font Awesome in QML? I couldn't find any document or any information how to use Font Awesome in QML.

like image 578
NTMS Avatar asked Dec 13 '17 08:12

NTMS


2 Answers

What I like to do is use fontello to create a minimal set of icons, rather than downloading the whole set from FontAwesome. Using the texteditor example as a reference:

  1. Download the font and store it somewhere in your project directory. In the example, it's in the fonts folder.
  2. If you're using .qrc files in your project, add it to one of those.
  3. There are two ways that I can think of to have the font recognised in your QML: FontLoader and QFontDatabase::addApplicationFont(). To use QFontDatabase::addApplicationFont(), add this code before loading your application's QML:

    QFontDatabase fontDatabase;
    if (fontDatabase.addApplicationFont(":/fonts/fontello.ttf") == -1)
        qWarning() << "Failed to load fontello.ttf";
    
  4. Use the Unicode codes in the text property of whatever item you want to display the icon in:

    ToolButton {
        id: openButton
        text: "\uF115" // icon-folder-open-empty
        font.family: "fontello"
        onClicked: openDialog.open()
    }
    
like image 144
Mitch Avatar answered Oct 19 '22 22:10

Mitch


There is a solution here : https://martin.rpdev.net/2018/03/30/using-fontawesome-5-in-qml.html

I personnaly mixed it with this solution for FontAwesome 4.7 which gives me this :

Item {
    id: awesome

    property alias icons: variables

    readonly property FontLoader fontAwesomeRegular: FontLoader {
        source: "./fa-regular-400.ttf"
    }
    readonly property FontLoader fontAwesomeSolid: FontLoader {
        source: "./fa-solid-900.ttf"
    }
    readonly property FontLoader fontAwesomeBrands: FontLoader {
        source: "./fa-brands-400.ttf"
    }

    readonly property string regular: fontAwesomeRegular.name
    readonly property string solid: fontAwesomeSolid.name
    readonly property string brands: fontAwesomeBrands.name

    Awesome.Variables {
        id: variables
    }
}

And Awesome.Variables is another file where I linked the icon names with their character code. Here is an excerpt :

QtObject {
    readonly property string fa_500px                               : "\uf26e"
    readonly property string fa_accessible_icon                     : "\uf368"
    readonly property string fa_accusoft                            : "\uf369"
    readonly property string fa_address_book                        : "\uf2b9"
    readonly property string fa_address_card                        : "\uf2bb"
}

In order to use it, I load it in my root Item, or in the one where I need an icon like this :

FontAwesome {
     id: awesome
}

Then use it like this :

Text{
    iconFont: awesome.solid
    text: awesome.icons.fa_arrow_up
}
like image 34
SThor Avatar answered Oct 19 '22 22:10

SThor