3
votes

I've been loosely following the article on Christophe Dumez's blog to get a custom QAbstractListModel class to expose the data to a QML (QtQuick2) interface (QtQuick2ApplicationViewer). However, since I'm using Qt 5.0.0 (and MSVC2012), there are some parts of his article that don't apply. For example, the ListModel constructor no longer has to call setRoleNames(), because setRoleNames() has been depreciated in Qt 5.

ListModel::ListModel(ListItem* prototype, QObject *parent) :
    QAbstractListModel(parent), m_prototype(prototype)
{
  setRoleNames(m_prototype->roleNames());
}

It is my understanding that the class that inherits from QAbstractListModel must only define roleNames(), as it has been changed to be a purely virtual function in Qt 5. So in his example, I simply comment out setRoleNames(m_prototype->roleNames()); in the constructor and everything should work. Right?

But instead, all of the defined roles are undefined, when accessed through QML. I can check the names in C++ with this:

QHash<int, QByteArray> mynames = model->find("Elephant")->roleNames();
qDebug() << "Model: " << mynames;

In this case, the role names for the Elephant object print as expected.

Are my assumptions correct, or do I need to do something else to get a QAbstractListModel object to share list element properties with QML2? This seems like a stupid question, but the Qt5 docs are so broken right now, I can't figure it out.

Thanks!

1
For people wondering how to implement this,github.com/jdahlbom/QtQmlListModel. Credit goes to jdahlbom.RajaRaviVarma

1 Answers

9
votes

You need to reimplement QAbstractListModel::roleNames() const method and your roles get registered in QML automatically.

There's a working example of an exposing QAbstractListModel-based model to QML at examples/quick/modelviews/abstractitemmodel.

You can also consider usage of QQmlListProperty.