I am using Pyside2 with QML, and try to keep a good organisation of my code.
I want to expose a subclass MyModel
of QAbstractListModel
from Python to QML, to use in a ListView
. The code works perfectly if I declare the MyModel
instance directly inside the engine:
...
engine = QQmlApplicationEngine()
myModel = MyModel(some_dict)
engine.rootContext().setContextProperty("myModel ", myModel)
...
that I can then use so:
ListView {
model: myModel
delegate: Row {
Text { text: name }
Text { text: type }
}
}
However, when I try to define this element as a Property
of a class, to keep things tidy and not registering models all over the place, I can't seem to make it work. I fail to recover good debugging information from qml, which also does not help.
I tried to declare the following
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 )
and then use it so in qml
ListView {
model: modelProvider.myModel
// or model: modelProvider.myQVariantModel
delegate: Row {
Text { text: name }
Text { text: type }
}
}
The result is a blank screen.
I found out there that one potential reason could be that QAbstractListModel
is a QObject
, which would make it non copyable, and in c++ they propose to pass a pointer to it instead. But I thought that this would be the case automatically in Python.
What do I do wrong in this case? And if possible, how could I find out why is the ListView
not rendering anything (a debug output, maybe)? Is it not possible at all to organize my code in this way?
For the context, I try to follow the Bloc pattern, that I enjoy a lot using with dart
and flutter
, in which you have one (or more) central Bloc
class that expose the model and the methods to act on this model for the view.