Python 从QML访问qresource文件中的映像 我试图将我的C++ QT应用程序移植到PyStR2。在我的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 }

Python 从QML访问qresource文件中的映像 我试图将我的C++ QT应用程序移植到PyStR2。在我的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 },python,qml,pyside2,qresource,Python,Qml,Pyside2,Qresource,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 = QQmlApplica

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_())
<RCC>
    <qresource prefix="/">
        <file>qml/main.qml</file>
        <file>qml/test.qml</file>
    </qresource>
</RCC>
qml.qrc
看起来像:

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_())
<RCC>
    <qresource prefix="/">
        <file>qml/main.qml</file>
        <file>qml/test.qml</file>
    </qresource>
</RCC>

qml/main.qml
qml/test.qml
我通过运行以下命令编译资源QRC文件:
$pipenv run pyside2 rcc-o src/ui/resources\u rc.py src/ui/resources.QRC

然后我通过运行:
pipenv run pyside2 rcc-o src/ui/QML\u rc.py src/ui/QML.QRC

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

UI将弹出,但控制台中有一些错误,特别是:


qrc:/qml/test.qml:25:9:qml-Image:无法打开:qrc:/resources/images/logo.svg

与导入qml\u-rc的方式相同,您还必须处理资源:

导入qml\u rc
输入资源

注意:用作组件的文件名必须大写,如所示,我假设test.qml只是用于示例的名称,在我的测试中,我使用了test.qml。

Ah,我导入了
qml\u rc
,但没有导入
resources\u rc
,因为我没有直接从Python代码中引用
resources\u rc
中的任何内容。
resources\u rc
中的所有内容都引用自我的QML代码。那是我的困惑。修正@环游世界与C++不同,在C++中QFile在可执行文件中查找资源,python执行导入的操作,因为如果您检查*_rc.py,您将看到有对数据的引用。是的
test.qml
只是我的示例,在我的实际代码中,文件名的大小写正确。