2012-12-31 5 views
3

Qt 모델은 QAbstractListModel 일 수 있습니다. 각 "행"은 내가 QList에 저장 한 객체를 나타냅니다. QMLListView으로 표시하고 있습니다. 그러나 각 객체에는 문자열 배열 인 하나의 속성이 있습니다. 해당 행을 표시하는 위임 내에 ListView으로 표시하고 싶습니다. 하지만 그 모델 (개체의 문자열 배열 속성)을 QML에 노출하는 방법을 모르겠습니다. 모델이 이므로 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 :: fromValue (myModelInstancePointer);'QVariant :: fromValue ' 또한 모델을'QVariant'로 나타낼 수 있습니다. –