3

I have a project with several QML files. All of them are inside resource file. Now I want to load external image, from local file system. But I cannot find a way to do that.

Image {
    source: "images/image.png" // that tries to load file as 'qrc:/images/image.png'
    source: "file://images/image.png" // that does not work (file not found)
}

So now I'm a bit confused, how can I load the file in right way?

Nejat
  • 31,784
  • 12
  • 106
  • 138
folibis
  • 12,048
  • 6
  • 54
  • 97

2 Answers2

5

The QML engine assumes that relative paths addressed in QML files stored in the Qt Resource System are resolved within that resource file. So if your QML file is in a resource and you want to access a file in the application directory path you should set the path from c++ :

engine.rootContext()->setContextProperty("applicationPath", "file://"+qApp->applicationDirPath()+ "/");

Now you can address the file in QML :

Image {
    source: applicationPath + "images/image.png"
}
Nejat
  • 31,784
  • 12
  • 106
  • 138
  • 1
    I discovered this recently, and this is the correct answer. I'd also suggest linking to http://doc.qt.io/qt-5/qml-url.html and quoting it: "A relative URL is resolved relative to the URL of the containing component." You say that "all relative paths in QML should also be resolved within that resource file", but it's a bit misleading, because it's not just specific to resource files. – Mitch Feb 07 '15 at 09:28
  • Thanks @Nejat. Mainly I was looking for a solution with only QML but as I see it's impossible to set up a url relative to app from resourse. – folibis Feb 07 '15 at 15:26
1

Thank you for this post. I worked on this code and saw that it didn't work for me. I finally realized where the problem was. Just use / instead of //.

context->setContextProperty("applicationPath","file:/"+qApp->applicationDirPath()+"/");
Rozety
  • 21
  • 1