首页 文章

除了使用项目角色之外,如何以QML(通过委托)访问存储在QAbstractListmodel中的项目?

提问于
浏览
4

我只想使用QML显示列表中的元素,但不使用项目角色 . 对于前者我想调用一个方法getName(),它返回要显示的项的名称 .

可能吗?我没有发现任何明显的反应 .

1 回答

  • 8

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

    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 . 否则,从数据方法返回的所有对象都将在QML端进行垃圾收集 .

相关问题