问题描述
我想在QML中使用QAbstractListModel派生模型.将模型绑定到视图已经很好用了.
I want to use an QAbstractListModel derived model in QML. Binding the model to views already works great.
我要实现的下一件事情是访问特定项目及其角色的能力,就像使用QML ListModel一样
The next thing I want achieve is the ability to access specific items and their role like it is possible with a QML ListModel
grid.model.get(index).DisplayRole
但是我不知道如何在我的QAbstractListModel派生模型中实现此get方法.
But I have no idea how to implement this get method in my QAbstractListModel derived model.
有任何提示吗?
推荐答案
您可以将Q_INVOKABLE函数添加到QAbstractItemModel派生类中,如下所示:
You can add an Q_INVOKABLE function to the QAbstractItemModel derived class like this:
...
Q_INVOKABLE QVariantMap get(int row);
...
QVariantMap get(int row) {
QHash<int,QByteArray> names = roleNames();
QHashIterator<int, QByteArray> i(names);
QVariantMap res;
while (i.hasNext()) {
i.next();
QModelIndex idx = index(row, 0);
QVariant data = idx.data(i.key());
res[i.value()] = data;
//cout << i.key() << ": " << i.value() << endl;
}
return res;
}
这将返回类似{ "bookTitle" : QVariant("Bible"), "year" : QVariant(-2000) }
的内容,因此您可以在其上使用.bookTitle
This will return something like { "bookTitle" : QVariant("Bible"), "year" : QVariant(-2000) }
so you could use .bookTitle on it
这篇关于如何为QAbstractListModel派生模型实现类似get方法的QML ListModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!