Home > Software design >  Can't load image file on QML if I don't specify the full path
Can't load image file on QML if I don't specify the full path

Time:10-15

new bee here and stuck with something simple. I have to build a large project with several images. They will be distributed hierarchically in different folders. However, even if I set a file alias="myimage.qml" I still need to add the full path to load the image propely. This is not what I want. In other words:

here is my qml.qrc

<qresource prefix="/View/Images">
    <file alias="db_normal.png">View/Images/db_normal.png</file>
    <file alias="db_pressed.png">View/Images/db_pressed.png</file>
</qresource>

but when I tried to load the resource as such:

Image
{
    id: buttonId
    source: "db_normal.png"

it does not work, only if I specify the full path as below:

Image
{
    id: buttonId
    source: "qrc:/View/Images/db_normal.png"

but this sort of goes against what I am trying to do. I will have several images and several QMl files I'd like not to specify the full path on everything. The code will look very ugly.

I can always do something like:

property string rscRoot: "qrc:/View/Images/"

Image
{
    id: buttonId
    source: rscRoot   "qc_normal.png"

but again, I don't want to create path variable everywhere. Is there a way to do make this work:

Image
{
    id: buttonId
    source: "db_normal.png"

with the file alias or other method?

thank you.

CodePudding user response:

As commented above you should get rid of the prefix path just use prefix="/".

<RCC>
    <qresource prefix="/">
        <file alias="test1">images/test1.jpg</file>
        <file>images/test2.jpg</file>
        <file>images/test3.jpg</file>
    </qresource>
</RCC>

import QtQuick

Window {
    width: 800
    height: 1000
    visible: true
    title: qsTr("Hello World")

    Column {
        Image {
            source: "qrc:/test1"
        }
        Image {
            source: "qrc:/images/test2.jpg"
        }
        Image {
            source: "qrc:/images/test3.jpg"
        }
    }
}
  • Related