Universal solution for resource prefix.
-
This code
@ QUrl url("qrc:/images/image.gif");
qDebug() << url.toLocalFile();
@
shows empty string :(I show example of what I want:
@
...
QString Settings::resourcePath()
{
return ":"; // or it may be "/home/user/program/data/" path
}...
QListWidgetItem *item = new QListWidgetItem("Item" , QIcon(settings->resourcePath() + "/icons/item.png"));
...
QDeclarativeView view;
...
view.setSource(QUrl(settings->resourcePath() + "/scripts/main.qml")); // Don't work for ":", QUrl think that this is local path.@
-
Volker
Settings::resourcePath() can return ':' or local path or (may be) http url, it is setting and user will set it in configuration file.
And it worked for url and local file, but it don't worked for resources, because QUrl don't able convert ":/" prefix to qrc protocol -
Please fix the post - the Quotes add a link, maybe you should wrap it to the source tags.
For QUrl: you must add the qrc scheme (protocol) to the string!
@
// ok:
QUrl validUrl("qrc:/path/to/main.qml");// bad:
// bascially resolves to "file:///path/to/main.qml"
QUrl badUrl(":/path/to/main.qml"); // bad
@The latter is treated like a file:// URL.
-
So why not add two methods to your Settings:
@
QString prefix; // set it to ":/" or "/path/to/home"QString getFilePrefix() {
return prefix;
}QString getUrlPrefix() {
return prefix.startsWith(":/") ? "qrc" + prefix : prefix;
}
@And then use the right one - you know in advance when if you construct an URL or a file path.
-
[quote author="bunjee" date="1302365361"]Interesting post.
From my perspective when you set a QUrl to "qrc:/myFile" then QUrl.toLocalFile() should return ":/myFile" instead of an empty string.
I guess there is a good reason for not doing this.[/quote]
At least at first sight, I think that would be a sensible thing to do. Why don't you file a feature request for that on Jira. If it isn't possible, you might get a response explaining why that would be the case.
-
just a small update here.
I have tried adding an image file from outside of qrc file and it works successfully. I have used something like this,
@QString path = "D:/logo.png";
engine.rootContext()->setContextProperty("logoPath", QUrl::fromLocalFile(path));
@
The "logoPath" can be used in the QML file, for example
@
Image
{
source: logoPath
}@ -
The trick to make QDir (QFile/QPixmap and others) to accept and work with QUrl pointing to both local file ("file:" schema or no schema) or QRC ("qrc:" schema) is to add a search path:
QDir::setSearchPaths("qrc", QStringList(":/"));
Now for the following
QUrl url("qrc:///images/image.gif"); QDir(url.toString()).exists();
will work as File System will consider "qrc" as search path and finally will look for ":///images/image.gif".
NOTE: the use of toString(), not toLocalFile().Obviously using the same url for anything that needs QUrl will work too.
QDeclarativeView view; view.setSource(url);