QML: how to specify image file path relative to application folder

Image {
   source: "file:resources/images/image.png"
}

will work if the working directory is set to the ApplicationFolder

note: when running from QtCreator, double check what directory the application is actually running in (i had my application run in my home directory even though the working directory was set correctly in the run configuration (after running it once in a terminal window this magically fixed itself) )


If you can't use a .qrc file for your images, you could try this:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("applicationDirPath", QGuiApplication::applicationDirPath());
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

In QML, you'd then do:

Image {
    source: "file:///" + applicationDirPath + "/../resources/images/image.png"
}

Note that this code is not tested.

Tags:

Qt

Qml

Qtquick2