How to access Items stored in a QAbstractListmodel in QML(by delegates) otherwise than using item roles?

独自空忆成欢 提交于 2020-01-10 05:09:28

问题


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.


回答1:


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_;
};

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.



来源:https://stackoverflow.com/questions/14423372/how-to-access-items-stored-in-a-qabstractlistmodel-in-qmlby-delegates-otherwis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!