2012-12-31 73 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);' –