FontLoader: Cannot load font - Solution
-
Re: QML FontLoader: Cannot load font
Took me months of troubleshooting to solve this. Below is an example of FontLoader:
FontLoader { id: myFont source: "myFont.ttf" }When you load the .qml file containing above code using qml.exe, it works fine. When you put the above code in .qml file within a Qt Quick project, and run using Qt Creator, the font doesn't load (despite copying myFont.ttf to bin directory). If you use a resource file, it still won't load. Keeps throwing the error, "QML FontLoader: Cannot load font...", or something similar. The issue is with the way resource and fonts files are processed and then embedded into the binary by CMake.
[Solution 1]
- Creat a resource file and add the font to it. i.e. resources.qrc:
<RCC>
<qresource prefix="/fonts">
<file>myFont.ttf</file>
</qresource>
</RCC> - Add the resources.qrc to qt_add_qml_module() under RESOURCES:
qt_add_qml_module(applearn-qt-quick
URI learn-qt-quick
VERSION 1.0
QML_FILES
Main.qml
RESOURCES
resources.qrc
) - Set CMAKE_AUTORCC variable to true in CMakeLists.txt:
set(CMAKE_AUTORCC ON) - Reference the font using the qrc url:
source: "qrc:/fonts/myFont.ttf"
[Solution 2]
- Creat a resource file and add the font to it. i.e. resources.qrc:
<RCC>
<qresource prefix="/fonts">
<file>myFont.ttf</file>
</qresource>
</RCC> - Add the resources.qrc to CMakeLists.txt using qt_add_resources():
qt_add_resources(RCC_SOURCES resources.qrc)
Note: above line of code should be before qt_add_executable(). - Add the RCC_SOURCES variable defined in step 2 to your qt_add_executable():
qt_add_executable(applearn-qt-quick
main.cpp
${RCC_SOURCES}
) - Reference the font using the qrc url:
source: "qrc:/fonts/myFont.ttf"
Warning: Don't add resources.qrc to qt_add_qml_module().
[Solution 3]
- Add the myFont.ttf to qt_add_qml_module() under RESOURCES:
qt_add_qml_module(applearn-qt-quick
URI learn-qt-quick
VERSION 1.0
QML_FILES
Main.qml
RESOURCES
myFont.ttf
) - Reference font using the follow url:
source: "myFont.ttf"
or
source: "qrc:/qt/qml/learn-qt-quick/myFont.ttf"
Note: replace learn-qt-quick with your own project name.
[Solution 4]
- Put myFont.ttf in the same directory as the app executable binary.
- Use the following url:
source: "file:myFont.ttf"
Hope this help. Thank you for your time and have a great day!
- Creat a resource file and add the font to it. i.e. resources.qrc:
-
M MapleKing has marked this topic as solved on
-
Helped a lot here, Sir! Thanks!
-
I had a similar issue recently where I was certain that a particular file was present in the qrc compiled resources, but the paths I was using to try to "get at" the file seemed to all be invalid guesses of the qrc file path.
Temporarily adding this snippet and looking at all the paths helped me solve it:
QDirIterator it(":", QDirIterator::Subdirectories); while (it.hasNext()) { qDebug() << it.next(); }