How to add and use a resource in QML?

I want to use the QtQuick Image object in a simple Qt project and include the image in the project. I added an image to the resource file. I used debugging to make sure that the resource exists and is compiled into the application as "Resources / myfile.png"

However, if I declare a QtQuick image object and set the source to "Resource / myfile.png", the image will not be found. Instead, I get a message:

QML Image: Cannot open: file:///C:/Users/me/Documents/QtCreator/build-myapp-Desktop_Qt_5_1_1_MinGW_32bit-Debug/qml/myapp/Resources/dial_bg.png 

The same thing happens if I try to use the C ++ approach to access the file

 source: ":/Resources/dial_bg.png" 

This causes a compilation error.

myfile.png was not copied to this location. myfile.png does not appear in project files, although it has been added to the resource file.

I will be pleased with the decision, which will either copy the image to the place where the image wants to pick it up, or the way for the image to access the โ€œcompiled inโ€ version.

+6
source share
2 answers

The way to access such resources in QML is as follows:

 source: "qrc:///Resources/dial_bg.png" 
+5
source

Qml.qrc file

 <!DOCTYPE RCC><RCC version="1.0"> <qresource prefix="/"> <file alias="main.qml">qml/main.qml</file> </qresource> <qresource prefix="/pics/"> <file alias="bottom_arrow.png">pics/bottom_arrow.png</file> </qresource> </RCC> 

In the main.cpp file to load the qml file:

 ... QString qml = QStringLiteral("qrc:///main.qml"); engine.load(QUrl(qml)); ... 

In the main.qml file to load the image:

 ... Image { source: "pics/ef-logo.png" } .. 

In QT, it is somehow an AUTORCC qrc file for code. But if you use Cmake and visual studio. then in Cmake you need to enable this:

 set(CMAKE_AUTOMOC ON) #must have for QML to work set(CMAKE_AUTORCC ON) #for compiling qrc file to rcc set(AUTORCC_OPTIONS "src/qml.qrc") 

Hope this helps. This may not be the best way, but still

0
source

Source: https://habr.com/ru/post/956966/


All Articles