lorow
lorow

Reputation: 23

How to get index of particular item in ListModel?

I've got a little problem with GridView component. I have to change some property of some objects during runtime. To do this, I can use the setProperty() function. However, this function needs index to work. And here the problem appears becouse, all items are created during runtime.

How can I get index of specific item?

Let me explain a little bit more. The item I'm reffering to is just a simple rectangle with MouseArea. Here's its code :

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

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

And here is my GridView code :

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
    }

And here is my code to dynamicly create items in 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);
            }
        }
    }
}

I don't really know how to get this index. Or I'm just blind and I'm missing something obvious.

Upvotes: 2

Views: 2166

Answers (1)

dtech
dtech

Reputation: 49289

There is an index attached property available for use inside the delegate. For every delegate instance it will correspond to the associated list model element index.

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

Upvotes: 2

Related Questions