Returning a custom class from a model using remote objects and qml
-
Hi,
Instead of assigning a role for each individual value of a model item and querying the values individually, is it possible to return an custom class from a model like this?
QVariant MyModel::data(const QModelIndex& index, int role) const { switch (role) { case MyModel::ItemRole: { return QVariant::fromValue<MyItem*>(m_items[index.row()]); } } return {}; }The MyItem class derives from QObject, does all the Q_DECLARE_METATYPE, qRegisterMetaType, qRegisterMetaTypeStreamOperators stuff and the stream operator overloads also exist:
QDataStream& operator<<(QDataStream& out, const MyItem* item); QDataStream& operator>>(QDataStream& in, MyItem* item);I've been trying for a while but somehow it doesn't seem to work. Whenever i want to access the items from qml
GridLayout { ... Repeater { // Pointer to the MyModel replica of type QAbstractItemModelReplica model: myModelReplica delegate: Item { // _item is the name of the MyModel::ItemRole property var myItem: _item ... } } }the operator>>() is called with a null pointer and after that a Out of memory occures:
Out of memory in C:\Users\qt\work\install\include\QtCore/qvector.h, line 709 -
-
@VRonin thank a lot for your help.
When using Q_GADGET instead of the Q_OBJECT macro I don't have to derive from QObject and can therefore use value semantics. So the stream operator overloads can use a reference parameter and everything works perfectly:
QDataStream& operator<<(QDataStream& out, const MyItem& item); QDataStream& operator>>(QDataStream& in, MyItem& item);