2012-12-31 70 views
3

我有一個Qt模型,很可能是一個QAbstractListModel。每個「行」代表我存儲在QList中的一個對象。我在QML中顯示ListView。但是,每個對象都有一個恰好是字符串數組的屬性。我想在顯示該行的委託中將其顯示爲ListView。但我不知道如何將該模型(對象的字符串數組屬性)公開到QML。由於模型是QObjects,我不能通過數據函數公開它,因爲它不能是QVariants。我想用QAbstractItemModel代替,但我仍然不知道如何獲得我的ListView模型。萬一它很重要,我使用Qt 5.0.0版本。模型中的Qt模型?

回答

3

您可以從主QAbstractListModel返回QVariantList,然後這可以被指定爲模型內部的ListView您在委託有。我添加了一個以內部模型爲例的非常簡單的單行模型的小例子。

C++模型類:

class TestModel : public QAbstractListModel 
{ 
    public: 

    enum EventRoles { 
    StringRole = Qt::UserRole + 1 
    }; 

    TestModel() 
    { 
    m_roles[ StringRole] = "stringList"; 
    setRoleNames(m_roles); 
    } 

    int rowCount(const QModelIndex & = QModelIndex()) const 
    { 
    return 1; 
    } 

    QVariant data(const QModelIndex &index, int role) const 
    { 
    if(role == StringRole) 
    { 
     QVariantList list; 
     list.append("string1"); 
     list.append("string2"); 
     return list; 
    } 
    } 

    QHash<int, QByteArray> m_roles; 
}; 

現在,你可以把這個模型QML,並使用它像這樣:

ListView { 
    anchors.fill: parent 
    model: theModel //this is your main model 

    delegate: 
    Rectangle { 
     height: 100 
     width: 100 
     color: "red" 

     ListView { 
     anchors.fill: parent 
     model: stringList //the internal QVariantList 
     delegate: Rectangle { 
      width: 50 
      height: 50 
      color: "green" 
      border.color: "black" 
      Text { 
      text: modelData //role to get data from internal model 
      } 
     } 
     } 
    } 
} 
+0

感謝。它也證明你可以將模型作爲'QVariant'公開爲:'QVariant :: fromValue (myModelInstancePointer);' –