Nulik Nulik - 19 days ago 7
C++ Question

Getting data by index from the C++ model in QML

How do you get the data from your model (sub-classed from

QAbstractItemModel
) outside of the delegate using QML?

I tried it like this:

Identities {
id: identities_model
}
...
console.log(identities_model[0].email)


but I get an error:

TypeError: Cannot read property 'email' of undefined


My
data()
method is defined like this:

QVariant Identities::data(const QModelIndex &index, int role) const {
int row_num;
row_num=index.row();
if (role==EmailRole) {
QList <QString> qlist;
qlist=identities_map.keys();
if (row_num>=qlist.size()) return (QVariant());
return QVariant(qlist.at(row_num));
}
if (role==PasswordRole) {
QList <QString> qlist;
qlist=identities_map.keys();
if (row_num>=qlist.size()) return (QVariant());
Identity *identity;
identity=identities_map.value(qlist.at(row_num));
return QVariant(identity->password());
}
if (role==Qt::DisplayRole) {
return(QVariant());
}
}


I tried to debug (put some breakpoints) but couldn't intercept any call to
Identities::data()
or
Identities::index()
towards my model from QML. How should I access data in my model outside of the delegate? (specific row, specific role) When I use delegates, my model works perfectly fine.

Answer

Just implement Identity * at(int index) slot or invokable function for the model. Then identities_model.at(0).email should work.

The roles are not at play here, as your Identity is a QObject derived, it should implement them as properties in order to be used in QML. The roles are only for the view delegate. Had it not been a QObject derived, you could use Q_GADGET to generate meta info for the type to make it accessible from QML.

The [] operator would work had your model been a JS array. Also, JS would not complain about your model not having a [] operator, it would simply give you an undefined because it is undefined. The same way it would be for something like this:

  var v = 3
  console.log(v[0])

JS doesn't support operator overloading, nor will it support any operators, implemented on the C++ side. Functions only.

Comments