Qt 如何访问存储在QML中QAbstractListmodel中的项(由委托访问),而不是使用项角色?

Qt 如何访问存储在QML中QAbstractListmodel中的项(由委托访问),而不是使用项角色?,qt,qml,Qt,Qml,我只想使用QML显示列表中的元素,但不使用项目角色。 例如,我想调用一个方法getName(),该方法返回要显示的项的名称 可能吗?我没有发现任何与此相关的明确信息。您可以使用一个特殊角色返回整个项目,如下所示: template<typename T> class List : public QAbstractListModel { public: explicit List(const QString &itemRoleName, QObject *parent =

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


可能吗?我没有发现任何与此相关的明确信息。

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

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_;
};
模板
类列表:公共QAbstractListModel
{
公众:
显式列表(常量QString&itemRoleName,QObject*parent=0)
:QAbstractListModel(父级)
{
QHash角色;
roles[Qt::UserRole]=QByteArray(itemRoleName.toAscii());
setRoleNames(角色);
}
无效插入(整数,其中T*项){
Q_断言(项目);
如果(!项)返回;
//这对于防止项目在JS中被垃圾收集是非常重要的!!!
QDeclarativeEngine::setObjectOwnership(项,QDeclarativeEngine::CppOwnership);
item->setParent(此项);
beginInsertRows(QModelIndex(),其中,其中);
项目插入(其中,项目);
endInsertRows();
}
public://qabstractemodel
int行计数(常量QModelIndex&parent=QModelIndex())常量{
Q_未使用(父母);
返回项目数();
}
QVariant数据(常量QModelIndex&index,int-role=Qt::DisplayRole)常量{
如果(index.row()<0 | | index.row()>=items.count()){
返回QVariant();
}
if(Qt::UserRole==角色){
QObject*item=items[index.row()];
返回QVariant::fromValue(项);
}
返回QVariant();
}
受保护的:
QList项目;
};
不要忘记在所有插入方法中使用。否则,从数据方法返回的所有对象将在QML端被垃圾收集