如何为 QAbstractListModel 派生模型实现 QML ListModel 之类的 get 方法 [英] How to implement QML ListModel like get method for an QAbstractListModel derived model

查看:22
本文介绍了如何为 QAbstractListModel 派生模型实现 QML ListModel 之类的 get 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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.

有什么提示吗?

推荐答案

你可以像这样向 QAbstractItemModel 派生类添加一个 Q_INVOKABLE 函数:

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 派生模型实现 QML ListModel 之类的 get 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆