【问题标题】:How to access Items stored in a QAbstractListmodel in QML(by delegates) otherwise than using item roles?除了使用项目角色之外,如何访问存储在 QML 中的 QAbstractListmodel 中的项目(通过委托)?
【发布时间】:2013-01-20 09:55:10
【问题描述】:

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

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

【问题讨论】:

    标签: qt qml


    【解决方案1】:

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

    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 端被垃圾收集。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 2018-07-11
      • 2016-10-30
      相关资源
      最近更新 更多