2013-01-20 15 views

回答

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端進行垃圾回收。

相關問題