将QAbstractListModel声明为Pyside2中的属性

问题描述 投票:1回答:1

我正在使用带有QML的Pyside2,并尝试保持良好的代码组织。我想将一个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,其中你有一个(或更多)中央Bloc类,它暴露模型和方法对该模型作用于视图。

python qt qml pyside2
1个回答
2
投票

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

卖弄.朋友

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 }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.