python - 如何用PyQt5为QML自定义一个Model
PHP中文网
PHP中文网 2017-04-17 17:47:22
0
0
399

我想在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__",好像datarowCountroleNames这3个函数都没有被调用,也许是我在qml中使用model的方式有错误。

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(0)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template