How to reference an image in QML

  • I'm a Java and Objective-C developer and new at Qt to develop apps on Sailfish OS. Therefore my question may sounds trivial for the most of you. I've created a simple example app to display an image for different page orientations on a smart phone.

    Therefore I have created a folder named "res" right under the root of the project directory. This resource folder contains the image "image.jpg".

    Afterwards I have added the resource to my example project. Thus the example project file "" contains the following lines:

    DISTFILES += \
        rpm/MyPageOrientationExample.spec \

    In my QML code I have defined an image:

          Image {
                     id: image
                     anchors {
                         top: header.bottom
                         horizontalCenter: page.isPortrait ? parent.horizontalCenter : undefined
                     sourceSize.width: {
                         var maxImageWidth = page.width
                         var leftMargin = Theme.horizontalPageMargin
                         var rightMargin = page.isPortrait ? Theme.horizontalPageMargin : 0
                         return maxImageWidth - leftMargin - rightMargin
                     fillMode: Image.PreserveAspectFit
                     source: "../res/image.jpg"

    If I build an run the project, I get the following error:

    [D] unknown:0 - QML debugging is enabled. Only use this in a safe environment.
    [D] unknown:0 - Using Wayland-EGL
    [W] unknown:46 - file:///usr/share/MyPageOrientationExample/qml/MyPageOrientationExample.qml:46:14: QML Image: Cannot open: file:///usr/share/MyPageOrientationExample/res/image.jpg

    Can someone help me?

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You are using a relative path. Since you are likely using Qt Creator, your application is built in an out of source folder (aka shadow build) which is not your source tree hence your error.

    You should consider using Qt's resources system to embed that image into your application.

  • Thanks for your response. Maybe other Qt beginners will have the same question. Thus I would like to summarise my solution:

    1. Select "Add" from the context menu of the project in QtCreator
    2. Select "Qt" and "QT Resource File" in the popup window
    3. Create a name for the resource file
    4. Select "Add Directory" from the context menu of the resource file
    5. Select your resource folder of the project within the popup window

    Im my code I used the following path:

    source: "qrc:///res/image.jpg"

  • Lifetime Qt Champion

    Nice summary !

    Since you have it working now, please mark the thread as solved using the "Topic Tools" button so that other forum users may know a solution has been found :)

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.