2016-09-02 40 views
2

我對GridView組件有點問題。我必須在運行時更改某些對象的某些屬性。爲此,我可以使用setProperty()函數。但是,此功能需要索引才能起作用。在這裏出現的問題因爲,所有項目都是在運行時創建的。如何獲取ListModel中特定項目的索引?

如何獲得特定項目的索引?

讓我再解釋一下。我正在嘗試的項目只是一個帶有MouseArea的簡單矩形。下面是它的代碼:

Rectangle { 
property var colorR 
id: namE 
width: 100 
height: 100 
color: colorR 

MouseArea { 
    id: mouseArea1 
    anchors.fill: parent 
    onClicked: 
    { 
     console.log(parent.nameIndex) 
    } 
} 
} 

這裏是我的GridView控件代碼:

GridView { 
     id: gridView1 
     anchors.rightMargin: 5 
     anchors.leftMargin: 5 
     anchors.bottomMargin: 5 
     anchors.topMargin: 10 
     anchors.fill: parent 
     flickableDirection: Flickable.VerticalFlick 
     snapMode: GridView.NoSnap 
     highlightRangeMode: GridView.NoHighlightRange 
     highlightMoveDuration: 148 
     flow: GridView.FlowLeftToRight 
     layoutDirection: Qt.RightToLeft 

     model: ListModel {id: listModelMy} 
     delegate: Column {ColorBlock{}} 

     cellHeight: 100 
     cellWidth: 100 
    } 

這裏是我的代碼,以動態地在GridView中

創建項目
Rectangle { 
     id: addButton 
     width: 65 
     height: 55 
     color: "#b04b4b" 
     border.color: "#252323" 
     anchors.bottom: parent.bottom 
     anchors.bottomMargin: 10 
     anchors.right: parent.right 
     anchors.rightMargin: 8 
     Image { 
      id: image1 
      anchors.rightMargin: 16 
      anchors.leftMargin: 16 
      anchors.bottomMargin: 10 
      anchors.topMargin: 10 
      anchors.fill: parent 
      source: "svgIcons/add.svg" 
     MouseArea { 
      id: mouseArea1 
      anchors.fill: parent 
      onClicked: 
      { 
       var test = listModelMy.append(ListElement); 
      } 
     } 
    } 
} 

我真的不知道該怎麼得到這個索引。或者我只是失明,我錯過了一些明顯的東西。

回答

1

有一個index附加屬性可用於委託內部。對於每個委託實例,它將對應於關聯的列表模型元素索引。

GridView { 
    anchors.fill: parent 
    model: ListModel { id: mod } 
    delegate: Rectangle { 
     width: 50 
     height: 50 
     color: "red" 
     Text { 
     text: index 
     anchors.centerIn: parent 
     } 
    } 
    } 
+0

我知道我錯過了一些明顯的東西!非常感謝您的幫助,它正在發揮作用。 :d – lorow

相關問題