使用 PySide2 从资源 (QRC) 文件导入 QML
Importing QML from a Resource (QRC) file with PySide2
我在我的“resource.qrc”文件中添加了一个简单的 QML 组件(“qml/MyButton”):
<RCC>
<qresource prefix="/">
<file>qml/MyButton.qml</file>
</qresource>
</RCC>
然后我将 QRC 编译成 python 模块:
pyside2-rcc -o resource.py resource.qrc
然后我在main.py中导入了resource.py:
import sys
import os
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
import resource
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
并在 main.qml 中调用了 MyButton 组件:
import QtQuick 2.13
import QtQuick.Window 2.13
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
MyButton {
}
}
这是“qml/MyButton.qml”:
import QtQuick 2.0
import QtQuick.Controls 2.13
Button {
text: 'Click Me'
}
当我 运行 程序时,我收到“MyButton 不是一种类型”的错误。我想通过使用 python 生成的资源文件来使用 QML 组件。我不知道我做错了什么。
如果 .qml 在主文件旁边,但在您的情况下 MyButton.qml 不在 main.qml 旁边,则自动导入,因此必须导入包:
import QtQuick 2.13
import QtQuick.Window 2.13
<b>import "qrc:/qml"</b>
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
MyButton {
}
}
我在我的“resource.qrc”文件中添加了一个简单的 QML 组件(“qml/MyButton”):
<RCC>
<qresource prefix="/">
<file>qml/MyButton.qml</file>
</qresource>
</RCC>
然后我将 QRC 编译成 python 模块:
pyside2-rcc -o resource.py resource.qrc
然后我在main.py中导入了resource.py:
import sys
import os
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
import resource
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
并在 main.qml 中调用了 MyButton 组件:
import QtQuick 2.13
import QtQuick.Window 2.13
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
MyButton {
}
}
这是“qml/MyButton.qml”:
import QtQuick 2.0
import QtQuick.Controls 2.13
Button {
text: 'Click Me'
}
当我 运行 程序时,我收到“MyButton 不是一种类型”的错误。我想通过使用 python 生成的资源文件来使用 QML 组件。我不知道我做错了什么。
如果 .qml 在主文件旁边,但在您的情况下 MyButton.qml 不在 main.qml 旁边,则自动导入,因此必须导入包:
import QtQuick 2.13
import QtQuick.Window 2.13
<b>import "qrc:/qml"</b>
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
MyButton {
}
}