Search code examples
qtqmlqresource

qt resources what is the correct form to use resource in qml qrc:///bg.png vs ../bg.png


Good morning i have a question for qt experts, i want to know what is the correct form and best for performance to use a resource inside qrc, for example i have:

1-

    Image {
        id: bg
        anchors.bottomMargin: 60
        anchors.fill: parent
        source: "qrc:///assets/img/drawable-hdpi/bg.png"
    }

2-

    Image {
        id: bg
        anchors.bottomMargin: 60
        anchors.fill: parent
        source: "../assets/img/drawable-hdpi/bg.png"
    }

whit the first qtcreator in design mode dont show the bg image but in preview or emulator works

whit the second qtcreator in design mode show the image and also work in preview

also whit this form:

    Image {
        id: bg
        anchors.bottomMargin: 60
        anchors.fill: parent
        source: "qrc:/assets/img/drawable-hdpi/bg.png"
    }

works in preview but qtcreator in design mode dont show the bg.png

i read in some qtblog post that if you want to use cache or somethink like that you need to use resources as qrc:// but i cant found the link right now.

but i want to know what is the best form and also for what using qrc:// qtcreator in design mode cant show the resource.


Solution

  • Qt resource compiler (qrc) generates C files that contain the binary files, and those then get compiled and linked into the executable, and there's no caching of binary data involved within Qt.

    The path you use to access the resource makes no difference performance-wise: if some top-level QML file was loaded using an absolute qrc:// protocol, then all the children that have relative paths will be loaded from the resources compiled into the executable, not from the OS filesystem (and that'd fail, since these files are not within the build/installation folder by the time the executable runs).

    Since the executable is usually memory-mapped (as-if you did a mmap on the executable file), accessing resources is about as fast as accessing contents of a memory-mapped file, i.e. probably the fastest way to access anything via an OS. Paths have little to do with it.

    Of course, paths have to be parsed, but that has a relatively low cost. I haven't checked this, but Qt's implementation of the qrc "filesystem" could hash the URI's and match these hashes to the resource table, and only parse the path if that fails - but I'm not sure that any performance improvement there is worth it unless you're on a very resource-constrained system. Now, if this hashing behavior was a part of the API (i.e. it was documented that Qt has to behave this way), then it'd be prudent to design your software to take advantage of it, so as not to prematurely pessimize. In absence of such API guarantees, I wouldn't worry about it, since whatever micro-optimization you do based on implementation details, may make things worse in the next Qt version.