Nulik Nulik - 1 year ago 145
C++ Question

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

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

) outside of the delegate using QML?

I tried it like this:

Identities {
id: identities_model

but I get an error:

TypeError: Cannot read property 'email' of undefined

method is defined like this:

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

I tried to debug (put some breakpoints) but couldn't intercept any call to
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 Source

Just implement Identity * at(int index) slot or invokable function for the model. Then 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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download