资源内的文件找不到本地文件
File inside resource cannot find local file
我有一个包含多个 QML
文件的项目。它们都在资源文件中。现在我想从本地文件系统加载外部图像。但是我找不到办法做到这一点。
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)
}
所以现在我有点困惑,我怎样才能以正确的方式加载文件?
QML 引擎假定存储在 Qt 资源系统中的 QML 文件中寻址的相对路径在该资源文件中得到解析。因此,如果您的 QML 文件在资源中,并且您想要访问应用程序目录路径中的文件,您应该从 C++ 设置路径:
engine.rootContext()->setContextProperty("applicationPath", "file://"+qApp->applicationDirPath()+ "/");
现在您可以在 QML 中寻址文件了:
Image {
source: applicationPath + "images/image.png"
}
谢谢你 post。我研究了这段代码,发现它对我不起作用。我终于意识到问题出在哪里了。只需使用 / 而不是 //.
context->setContextProperty("applicationPath","file:/"+qApp->applicationDirPath()+"/");
我有一个包含多个 QML
文件的项目。它们都在资源文件中。现在我想从本地文件系统加载外部图像。但是我找不到办法做到这一点。
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)
}
所以现在我有点困惑,我怎样才能以正确的方式加载文件?
QML 引擎假定存储在 Qt 资源系统中的 QML 文件中寻址的相对路径在该资源文件中得到解析。因此,如果您的 QML 文件在资源中,并且您想要访问应用程序目录路径中的文件,您应该从 C++ 设置路径:
engine.rootContext()->setContextProperty("applicationPath", "file://"+qApp->applicationDirPath()+ "/");
现在您可以在 QML 中寻址文件了:
Image {
source: applicationPath + "images/image.png"
}
谢谢你 post。我研究了这段代码,发现它对我不起作用。我终于意识到问题出在哪里了。只需使用 / 而不是 //.
context->setContextProperty("applicationPath","file:/"+qApp->applicationDirPath()+"/");