从 QML 访问 qresource 文件中的图像



我正在尝试移植我的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>

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

然后我通过运行以下命令编译我的 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

注意:用作组件的文件的名称必须按照规则 M16 的指示大写,我想 test.qml 只是用于示例的名称,在我的测试中我使用了 Test.qml。

最新更新