从 QML 访问 qresource 文件中的图像

Access image in qresource file from QML

我正在尝试移植我的 C++ Qt 应用程序以使用 PySide2。在我的 QML 中,我有以下内容:

# test.qml
Image {
    Layout.fillWidth: true
    Layout.leftMargin: 5
    Layout.rightMargin: 5
    source: "qrc:/resources/images/logo.svg" # <-- Problematic line
    fillMode: Image.PreserveAspectFit
    asynchronous: true
}

我的 logo.svg 文件在我的 resources.qrc 文件中被引用,如下所示:

<RCC>
    <qresource prefix="/">
        <file>resources/images/logo.svg</file>
    </qresource>
</RCC>

main.py 看起来像:

import sys

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QUrl

import qml_rc

if __name__ == '__main__':
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.load("qrc:/qml/main.qml")

    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())

qml.qrc 看起来像:

<RCC>
    <qresource prefix="/">
        <file>qml/main.qml</file>
        <file>qml/test.qml</file>
    </qresource>
</RCC>

我通过 运行ning 编译我的资源 QRC 文件:$ pipenv run pyside2-rcc -o src/ui/resources_rc.py src/ui/resources.qrc.

然后我通过 运行ning 编译我的 QML QRC 文件:pipenv run pyside2-rcc -o src/ui/qml_rc.py src/ui/qml.qrc

然后我 运行 我的程序使用以下命令:pipenv run python src/ui/main.py

UI 会弹出,但控制台会出现一些错误,特别是:

qrc:/qml/test.qml:25:9: QML Image: Cannot open: qrc:/resources/images/logo.svg

以与导入 qml_rc 相同的方式,您还必须使用 resources_rc:

import qml_rc
import resources_rc

注意:作为组件的文件名必须大写,如rule M16所示,我想test.qml只是一个示例中使用的名称,在我的测试中我使用了 Test.qml.