在Pyside2中将QAbstractListModel声明为属性

时间:2019-02-14 10:14:21

标签: python qt qml pyside2

我将Pyside2与QML结合使用,并尝试保持代码的良好组织。 我想公开MyModel的子类QAbstractListModel从Python到QML,以便在ListView中使用。如果我直接在引擎内部声明MyModel实例,则代码可以正常工作:

...
engine = QQmlApplicationEngine()
myModel = MyModel(some_dict)
engine.rootContext().setContextProperty("myModel ", myModel)
...

然后我可以这样使用:

ListView {
    model: myModel
    delegate: Row {
        Text { text: name }
        Text { text: type }
    }
}

但是,当我尝试将此元素定义为类的Property时,为了使事情保持整洁并且不在各处注册模型,我似乎无法使其正常工作。我无法从qml中恢复良好的调试信息,这也无济于事。

我试图声明以下内容

class ModelProvider(QObject):
    modelChanged = Signal()
    _entries: List[Dict[str, Any]]

    def __init__(self, entries, parent=None):
        QObject.__init__(self, parent)
        self._entries = entries

    def _model(self):
        return MyModel(self._entries)

    myModel = Property(list, _model, notify=modelChanged)
    myQVariantModel = Property('QVariantList', _model, notify=modelChanged)

...
modelProvider = ModelProvider(some_dict)
engine.rootContext().setContextProperty("modelProvider", modelProvider )

然后在qml中使用它

ListView {
    model: modelProvider.myModel
    // or model: modelProvider.myQVariantModel 
    delegate: Row {
        Text { text: name }
        Text { text: type }
    }
}

结果是黑屏。

我发现there可能的原因可能是QAbstractListModelQObject,这使其无法复制,因此在c ++中,他们建议将指针传递给它。但是我认为Python会自动出现这种情况。

在这种情况下我该怎么办?并且,如果可能的话,我如何找出ListView为什么不呈现任何内容(可能是调试输出)?这样根本不可能组织我的代码吗?


在上下文中,我尝试遵循Bloc模式,在dartflutter的使用中我非常喜欢,其中您有一个(或多个)中央{{ 1}}类,它公开了模型以及对该视图执行操作的方法。

1 个答案:

答案 0 :(得分:1)

您必须指出,该属性是QObject,而不是QVariantList或列表。另一方面,我不认为您更改了模型,因此您应该使用常量属性并且没有信号。另外,您不相信Model函数,因为每次调用_model都会创建一个不同的对象。

main.py

import os
import sys
from functools import partial
from PySide2 import QtCore, QtGui, QtQml

class MyModel(QtCore.QAbstractListModel):
    NameRole = QtCore.Qt.UserRole + 1000
    TypeRole = QtCore.Qt.UserRole + 1001

    def __init__(self, entries, parent=None):
        super(MyModel, self).__init__(parent)
        self._entries = entries

    def rowCount(self, parent=QtCore.QModelIndex()):
        if parent.isValid(): return 0
        return len(self._entries)

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if 0 <= index.row() < self.rowCount() and index.isValid():
            item = self._entries[index.row()]
            if role == MyModel.NameRole:
                return item["name"]
            elif role == MyModel.TypeRole:
                return item["type"]

    def roleNames(self):
        roles = dict()
        roles[MyModel.NameRole] = b"name"
        roles[MyModel.TypeRole] = b"type"
        return roles

    def appendRow(self, n, t):
        self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
        self._entries.append(dict(name=n, type=t))
        self.endInsertRows()

class ModelProvider(QtCore.QObject):
    def __init__(self, entries, parent=None):
        super(ModelProvider, self).__init__(parent)
        self._model = MyModel(entries)

    @QtCore.Property(QtCore.QObject, constant=True)
    def model(self):
        return self._model

def test(model):
    n = "name{}".format(model.rowCount())
    t = "type{}".format(model.rowCount())
    model.appendRow(n, t)

def main():
    app = QtGui.QGuiApplication(sys.argv)
    entries = [
        {"name": "name0", "type": "type0"},
        {"name": "name1", "type": "type1"},
        {"name": "name2", "type": "type2"},
        {"name": "name3", "type": "type3"},
        {"name": "name4", "type": "type4"},
    ]
    provider = ModelProvider(entries)
    engine = QtQml.QQmlApplicationEngine()
    engine.rootContext().setContextProperty("provider", provider)
    directory = os.path.dirname(os.path.abspath(__file__))
    engine.load(QtCore.QUrl.fromLocalFile(os.path.join(directory, 'main.qml')))
    if not engine.rootObjects():
        return -1
    timer = QtCore.QTimer(interval=500)
    timer.timeout.connect(partial(test, provider.model))
    timer.start()
    return app.exec_()

if __name__ == '__main__':
    sys.exit(main())

main.qml

import QtQuick 2.11
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

ApplicationWindow {    
    visible: true
    width: 640
    height: 480
    ListView {
        model: provider.model
        anchors.fill: parent
        delegate: Row {
            Text { text: name }
            Text { text: type }
        }
    }
}
相关问题