The purpose of this post is to create a battery charge level indicator in Qt/QML. For the buttery icon we’ll use Font Awesome, which is a free icon font, so that we don’t need to design the icon from scratch.
Here is the list of contents of this post.
Contents
– Steps
1. Download icon font and add to your project
2. Create “BatteryIcon” component
3. Use “BatteryIcon” component
– Summary
– Reference
Steps
1. Download icon font and add to your project
1-1. Download Font Awesome from here and extract the zip file.
1-2. Copy .ttf file to your Qt Creator project folder.
1-3. Then, right-click on “qml.qrc” and select “Add Existing Files…” in the left side bar.
1-4. Select .ttf file to add.
2. Create “BatteryIcon” component
2-1. In your Qt Creator project, click on “Resources” in the left side bar.
2-2. Then, right-click on “qml.qrc” and select “Add New…”
2-3. Select “Qt” and “QML File (Qt Quick2)”.
2-4. Input “BatteryIcon” as the file name and click on “Finish”.
2-5. Copy below lines to the file.
— BatteryIcon.qml —
import QtQuick 2.0 Item { property string iconColor property int iconSize: 32 // in pixcel property int level // 0-4 levels function getUnicode() { if (level == 0) return "\uf244" // fa-battery-empty else if (level == 1) return "\uf243" // fa-battery-quarter else if (level == 2) return "\uf242" // fa-battery-half else if (level == 3) return "\uf241" // fa-battery-three-quarters else if (level == 4) return "\uf240" // fa-battery-full else return "\uf244" // fa-battery-empty } Text { font.family: fontAwesome.name color: iconColor font.pixelSize: iconSize text: getUnicode() } FontLoader { id: fontAwesome; source: "qrc:/fontawesome-webfont.ttf" } }
2-6. Click on “qml.qrc” and “/” in the left side bar.
2-7. Right-click on the .ttf file and select “Copy URL …”.
2-8. Update URL on Line 31 with the URL copied at Step 2-7.
3. Use “BatteryIcon” component
3-1. Use BatteryIcon component like below example. It has three properties, icon color, icon size (in pixel) and battery level from 0 to 4 (0:empty, 1:quarter, 2:half, 3:three quarters and 4:full).
BatteryIcon{ iconSize: 48 iconColor: "blue" level: 2 }
If everything is fine, it will show like below battery icon.
I needed some icons for a project but was hesitant to create because I thought it’s gonna take some time. Then I found this article. It was really helpful for me at the situation, and Font Awesome is, yes, awesome! Using icon fonts for QML is makes sense. It requires less work, and it works perfectly.
– How to make a quick custom Qt/QML checkbox using icon fonts
https://medium.com/@eduard.metzger/how-to-make-a-quick-custom-qml-checkbox-using-icon-fonts-b2ffbd651144
– Font Awesome — The iconic font and CSS toolkit
http://fontawesome.io/icons/
Hello max,
fontawesome-webfont.ttf not exist in fontawesome version 5.
Can you recommend me another ttf file? Or can you update the article?
Thank you.