2017-10-20 295 views
0

我有一個適用於QTreeView的模型。在這個模型中,我實現一種看起來像這樣:QML TreeView是否支持從模型發出的信號layoutChanged?

void SimpleTreeModel::sort(Node* sortedNode) 
{ 
    emit layoutAboutToBeChanged(QList<QPersistentModelIndex>(), VerticalSortHint); 
    QModelIndexList oldIndices = persistentIndexList(); 

    Node::SortType sortType = Node::Down; 

    //sort starting node 
    sortedNode->sortChildren(sortType); 

    QModelIndexList newIndices; 
    newIndices.reserve(oldIndices.size()); 
    for(const auto &i : oldIndices) 
    { 
     Node* node = const_cast<Node*>(nodeFromIndex(i)); 
     QModelIndex index = indexFromNode(node); 
     newIndices.push_back(index); 
    } 
    changePersistentIndexList(oldIndices, newIndices); 

    QModelIndex startingIndex = indexFromNode(sortedNode); 
    emit layoutChanged({ QPersistentModelIndex(startingIndex) }, VerticalSortHint); 
} 

當我調用此函數,QTreeView則更新視圖,但在TreeView的QML不這樣做。 QML TreeView的用法:

TreeView 
{ 
    model: treeModel 
    TableViewColumn 
    { 
     title: "Title" 
     role: "title" 
     width: 700 
    } 
} 

我在做什麼錯?爲什麼視圖在排序後不更新元素的佈局?

回答

0

我認爲你需要委託樹視圖項目。數據提供給委託。

試着改變你的QML 的TreeView通過添加itemDelegate

TreeView 
{ 
    model: treeModel 

    itemDelegate: Item { 
     Text { 
       color: styleData.textColor 
       text: styleData.value 
      } 
    } 

    TableViewColumn 
    { 
     title: "Title" 
     role: "title" 
     width: 700 
    } 
} 

查找到下面的鏈接,瞭解代表的重要性,模型和QML視圖之間如下圖所示。有一個很容易解釋的圖像。

http://doc.qt.io/qt-5/qtquick-modelviewsdata-modelview.html

代表 - 決定如何將數據應該出現在視圖中。代理接收模型中的每個數據並封裝它。數據是 可通過委託人訪問。

+0

感謝您的回答。但我不明白這應該如何幫助。問題是TreeView不響應來自模型的信號。在閱讀了TreeView的源代碼之後,我沒有在其中找到負責響應模型信號layoutChanged的函數。它讓我困惑。 –

+0

@ strelok.ndv查看此鏈接,您將看到一個圖像以及如何委託以在QML視圖和模型之間進行通信。http://doc.qt.io/qt-5/qtquick-modelviewsdata-modelview.html – Naidu

+0

更新了答案。 – Naidu