QML 模型数据按索引 [英] QML Model data by index

查看:27
本文介绍了QML 模型数据按索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有基于 QAbstractListModel 的模型...

I have QAbstractListModel based model...

class RecordModel : public QAbstractListModel { ... };

QQmlContext *ctxt = engine.rootContext();
ctxt->setContextProperty("recordModel", &model);

// QML
recordModel.get(0).name // now work

如何通过索引和角色名称获取模型数据?

How to get a model data by index and role name?

... 解决方案:

// C++
class RecordModel : public QAbstractListModel
{
   Q_OBJECT
   Q_ENUMS(Roles)

   public:
      // ...
      Q_INVOKABLE QVariant data(int i, int role) const
      {
          return data(index(i, 0), role);
      }
};

// QML
recordModel.data(0, RecordModel.NameRole);

推荐答案

对于希望能够从 QML 调用的特定功能,您应该只使用 Q_INVOKABLE 方法.除非您想以某种方式访问​​模型数据而无需访问模型的委托,否则您应该始终使用更合适的模型<->委托方式来获取数据.

You should only use a Q_INVOKABLE method for specific functionalities that you want to be able to call from QML. Unless you somehow want to access model data from without access to the delegate of your model, you should always use the more proper model<->delegate way of getting the data.

因为您是从 QAbstractListModel 继承的,所以它会像 QAbstractItemModel 一样工作.

Since you're inheriting from QAbstractListModel, it'll work like QAbstractItemModel.

如图所示声明角色:

enum Roles {
    RoleA = Qt::UserRole + 1,
    RoleB = Qt::UserRole + 2
};

重写此方法以允许使用角色访问 QML:

Override this method to allow QML access using roles:

QHash<int, QByteArray> RecordModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[RoleA] = _Ut("roleA");
    roles[RoleB] = _Ut("roleB");
    return roles;
}

重写此方法以在 QML 尝试访问时返回数据:

Override this method to return data when QML tries to access:

QVariant RecordModel::data(const QModelIndex &modelIndex, int role) const
{
    QVariant rv;
    int index = modelIndex.row();

    switch( role ) {
    case RoleA:
        rv = "A";
        break;
    case RoleB:
        rv = "B";
        break;
    default:
        DASSERT(FALSE);     // Unexpected role.
        break;
    }

    return rv;
}

然后在 QML 中,您只需在使用此模型访问数据的 QML 元素的委托中使用roleA"和roleB".

Then in QML you'll simply use "roleA" and "roleB" in the delegates of the QML Element that uses this model to access the data.

参考文献:

http://qt-project.org/doc/qt-5.0/qtcore/qabstractitemmodel.html

http://qt-project.org/doc/qt-5.0/qtcore/qabstractlistmodel.html

这篇关于QML 模型数据按索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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