我想在PyQt5中自定义一个model,然后在qml中使用。我尝试写了一些代码,代码如下:
main.py
from PyQt5.QtCore import QAbstractListModel,Qt,QVariant,QModelIndex,QUrl,QObject
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import qmlRegisterType,QQmlComponent,QQmlEngine
class MyModel(QAbstractListModel):
def __init__(self,data):
super().__init__()
self.hexdata = data
print('__init__')
def data(self, index, role=None):
return self.hexdata[index.row()]
def rowCount(self, parent=None):
print('rowCount')
return len(self.hexdata)
def roleNames(self):
print('roleNames')
return 'lineData'
class Main(QObject):
pass
if __name__ == '__main__':
path = 'main.qml'
app = QApplication([])
view = QQuickView()
con = Main()
mymodel = MyModel(['1','2'])
qmlRegisterType(MyModel,'MyModel',1,0,'MyModel')
context = view.rootContext()
context.setContextProperty("con",con)
view.engine().quit.connect(app.quit)
view.setSource(QUrl(path))
view.show()
app.exec()
main.qml
import QtQuick 2.4
import MyModel 1.0
Rectangle {
property MyModel mymodel
width: 400
height: 500
ListView {
anchors.fill: parent
model: mymodel
delegate: Text{text: lineData}
}
}
运行代码时,只是弹出一个空白窗口,而且输出信息中,只有“__init__",好像data
、rowCount
、roleNames
这3个函数都没有被调用,也许是我在qml中使用model的方式有错误。
认证高级PHP讲师