除了使用项目角色之外,如何访问存储在 QML 中的 QAbstractListmodel 中的项目(通过委托)? [英] How to access Items stored in a QAbstractListmodel in QML(by delegates) otherwise than using item roles?

查看:9
本文介绍了除了使用项目角色之外,如何访问存储在 QML 中的 QAbstractListmodel 中的项目(通过委托)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想使用 QML 显示列表中的元素,而不是使用项目角色.例如.我想调用一个方法 getName() 来返回要显示的项目的名称.

I just want to display elements from list using QML, but not using item roles. For ex. I want to call a method getName() that returns the name of the item to be displayed.

有可能吗?我没有找到任何明确的参考.

Is it possible? I didn't find nothing clear reffering to this.

推荐答案

您可以使用一个特殊角色来返回整个项目,如下所示:

You can use one special role to return the whole item as you can see below:

template<typename T>
class List : public QAbstractListModel
{
public:
  explicit List(const QString &itemRoleName, QObject *parent = 0)
    : QAbstractListModel(parent)
  {
    QHash<int, QByteArray> roles;
    roles[Qt::UserRole] = QByteArray(itemRoleName.toAscii());
    setRoleNames(roles);
  }

  void insert(int where, T *item) {
    Q_ASSERT(item);
    if (!item) return;
    // This is very important to prevent items to be garbage collected in JS!!!
    QDeclarativeEngine::setObjectOwnership(item, QDeclarativeEngine::CppOwnership);
    item->setParent(this);
    beginInsertRows(QModelIndex(), where, where);
    items_.insert(where, item);
    endInsertRows();
  }

public: // QAbstractItemModel
  int rowCount(const QModelIndex &parent = QModelIndex()) const {
    Q_UNUSED(parent);
    return items_.count();
  }

  QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const {
    if (index.row() < 0 || index.row() >= items_.count()) {
      return QVariant();
    }
    if (Qt::UserRole == role) {
      QObject *item = items_[index.row()];
      return QVariant::fromValue(item);
    }
    return QVariant();
  }

protected:
  QList<T*> items_;
};

不要忘记使用 QDeclarativeEngine::setObjectOwnership你所有的插入方法.否则从 data 方法返回的所有对象都将在 QML 端被垃圾收集.

Do not forget to use QDeclarativeEngine::setObjectOwnership in all your insert methods. Otherwise all your objects returned from data method will be garbage collected on QML side.

这篇关于除了使用项目角色之外,如何访问存储在 QML 中的 QAbstractListmodel 中的项目(通过委托)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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