Search code examples
imageqtqmlresourcesdesktop

Why Resource Files Added in Qt Quick QML Project Are Not Displaying?


As in the title, added resources does not appear in my project:

Why do the attached .png files do not appear in center of window?

Why attached .png files does not appear in center of window?

Code:

import QtQuick

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Image {
        source: "://Images/empty.png"
        anchors.centerIn: parent
        visible: true
    }
}

What am I doing wrong, is it this QML source code matter or have I failed resource files attaching?

I really don't know where the problem is. It seems I am doing everything exactly like in tutorials and documentation.

Where is the mistake?

Edit:

This is qrc resource code:

<RCC>
<qresource prefix="/">
    <file>Images/cross.png</file>
    <file>Images/empty.png</file>
    <file>Images/nought.png</file>
</qresource>

Solution

  • You have 2 options. The first option would include to create a *.qrc file which contains all the assets and the assets/images are part of the project folder in some way.

    <RCC>
        <qresource prefix="/">
            <file>images/infinity.svg</file>
            <file>images/lockOff.svg</file>
            <file>images/search.svg</file>
        </qresource>
    </RCC>
    

    In this case you can use "relative" paths and also define your own names for files via aliases. Have a look at the documentation.

    Image {
        source: "qrc:/images/infinity.svg"
    }
    

    To make that work the build system needs to process the resource file. Have a look here. For CMake you need to set CMAKE_AUTORCC to true and add the *.qrc file to qt_add_executable()

    The second option would be to use the absolute path prefixed with file://. Sometimes you need to use Qt.resolveUrl() (documentation) to make it work.

    Image {
        source: "file://<absolute path to image>/images/infinity.svg"
    }
    

    I can't really explain why qrc:/... is working and :/... is not. It might be because the source property of Image is a url and the documentation says the following:

    You can also reference the Qt resource system through a QUrl. Use the qrc scheme in this case.