Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...