我试图使用qmlRegisterType扩展QML。我有一个python类 - PyQml.py,main.qml文件以及与之相关的样板代码。
问题在于我无法在main.qml文件中引用(导入)PyQml对象,我得到一个错误 --> QML模块未找到(PyQml)。
到目前为止,我已确定了QML_IMPORT_PATH变量路径。由于我很绝望,我在其中一个路径下创建了名为PyQml的文件夹,并将PyQml.py放入其中,但仍然没有成功。此外,在Qt Creator项目中,我找不到*.pro文件。我想我应该将另一个路径添加到自定义对象中。
PyQml.py
class PyQml(QObject):
def __init__(self, parent=None):
super().__init__(parent)
# Initialise the value of the properties.
self._name = ''
self._shoeSize = 0
# Define the getter of the 'name' property. The C++ type of the
# property is QString which Python will convert to and from a string.
@Property('str')
def name(self):
return self._name
# Define the setter of the 'name' property.
@name.setter
def name(self, name):
self._name = name
# Define the getter of the 'shoeSize' property. The C++ type and
# Python type of the property is int.
@Property(int)
def shoeSize(self):
return self._shoeSize
# Define the setter of the 'shoeSize' property.
@shoeSize.setter
def shoeSize(self, shoeSize):
self._shoeSize = shoeSize
qmlengine.py
import sys
import sqlite3
from PySide2 import QtCore, QtGui, QtWidgets, QtQuick
from PySide2.QtCore import Qt,QUrl
from PySide2.QtQml import QQmlApplicationEngine,qmlRegisterType
from PySide2.QtGui import QGuiApplication
from ViewModel import PyQml
if __name__ == '__main__':
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
print(QQmlApplicationEngine.importPathList(engine))
ctx = engine.rootContext()
ctx.setContextProperty("qmlapp", engine) #the string can be anything
qmlRegisterType(PyQml.PyQml, 'People', 1, 0, 'Person');
engine.load('Documents/ctmd/Qml/main.qml')
win = engine.rootObjects()[0]
win.show()
sys.exit(app.exec_())
main.qml
import QtQuick 2.0
import QtQuick.Controls 1.4
import PyQml 1.0 ---- Error QML module not found ( PyQml)
ApplicationWindow {
menuBar: MenuBar {
Menu {
title: "File"
MenuItem { text: "Open..." }
MenuItem { text: "Close" }
}
Menu {
title: "Edit"
MenuItem { text: "Cut" }
MenuItem { text: "Copy" }
MenuItem { text: "Paste" }
}
}
Grid {
columns: 3
spacing: 2
Rectangle { color: "red"; width: 50; height: 50 }
Rectangle { color: "green"; width: 20; height: 50 }
Rectangle { color: "blue"; width: 50; height: 20 }
Rectangle { color: "cyan"; width: 50; height: 50 }
Rectangle { color: "magenta"; width: 10; height: 10 }
}
}
项目文件夹树
Qml
-main.qml
PyQml.py
qmlengine.py
PyQml只是一个示例类,在一天的结束时,我想通过qml传递我在python中计算的自定义数据(x,y坐标),并用qml绘制这些数据。