2015-11-02 41 views
1

我的樹視圖顯示正確,但是當我單擊樹中的項目時,我無法獲取父母名稱。如何獲取樹視圖中選擇項的父母名稱QML

我的QML代碼可以在下面找到。

TreeView { 
    id:treeviewID 
    anchors.fill: parent 
    model: theModel 
    style: styleTreeView 
    selection: ItemSelectionModel{ 
     id:sel 
     model: theModel 
    } 
    headerVisible : true 
    selectionMode: SelectionMode.SingleSelection 

    onDoubleClicked:{ 

     console.log("parent Name of the Item selected : ",?????)  

    } 

    TableViewColumn { 
     role: "name_role" 
     title: valueSelected 
    } 
} 
+0

你能告訴我們你的模型嗎? – Tarod

+0

我解決了問題,我在我的模型C++中添加了一個函數,當我得到QModelIndex時。 – aryan

+0

太棒了!請發表您自己的答案,並將其標爲正確的;)快樂編碼! – Tarod

回答

0
I am resolved the problem and this is my solution: 
TreeView { 
    id:treeviewID 
    anchors.fill: parent 
    model: theModel 
    style: styleTreeView 
    selection: ItemSelectionModel{ 
     id:sel 
     model: myModel 
    } 
    headerVisible : true 
    selectionMode: SelectionMode.SingleSelection 

    itemDelegate: Rectangle { 
      id:r 
      height: 20 
      color:"transparent"  

      MouseArea{ 

       anchors.fill: parent 
       onClicked:{ 
        var indexSelected = styleData.index ; 
        var indexParent = indexSelected.parent; 
console.log("parent name is ",myModel.getParentName(indexParent)); 

       } 

    TableViewColumn { 
     role: "name_role" 
     title: valueSelected 
    } 
} 

MyModel is: 
TreeViewModel::TreeViewModel(QObject *parent) : QStandardItemModel(parent) 
{ } 
/** 
* @brief TreeViewModel::getParentName 
* @param itemIndex 
* @return string: name of parent item 
*/ 
QString TreeViewModel::getParentName(const QModelIndex &itemIndex){ 
    QVariant value1 = itemIndex.data(Qt::DisplayRole); 
    if(value1.isValid()) 
     return value1.toString(); 
    else 
     return QString(); 
}