How to access a ListView ListModel ListElement mapped delegate data in QML?

Essentially, I have a regular ListView:

Rectangle { id: mylist ListModel { id: mylistModel ListElement { text: "blah1" } ListElement { text: "blah2" } ListElement { text: "blah3" } } Component { id: mylistDelegate Text { id: mylistDelegateText text: text property bool mylistDelegateTextEnabled: false } } ListView { id: mylistView model: mylistModel delegate: mylistDelegate } } 

Please ignore any issues that I might introduce by truncating the code to focus on what is important.

Anyway, now the problem is that I want to access the assigned delegate ListElement and see that the value mylistDelegateTextEnabled is in the javascript loop. For example, this loop iterates over the current list and gives me the text ListElements in the model:

 for(var i = 0; i < mylistModel.count; ++i) { console.log(mylistModel.get(i).text); } 

This obviously works great.

Now I want essentially the following:

 for(var i = 0; i < mylistModel.count; ++i) { console.log(mylistModel.get(i).text); console.log(mylistModel.get(i).delegate.mylistDelegateTextEnabled); } 

Alas, that is not so simple.

Help evaluate.

+6
source share
2 answers

You cannot access delegates this way because they are temporary objects that are created and destroyed at the discretion of ListView . As explained in the documentation for delegates:

Delegates are created as needed and can be destroyed at any time. The state should never be kept as a delegate.

Is there a special reason why you cannot just add the textEnabled flag to the ListModel ? For instance:

 import QtQuick 1.0 Rectangle { id: mylist width:300 height:300 ListModel { id: mylistModel ListElement { name: "blah1" textEnabled:false } ListElement { name: "blah2" textEnabled:false } ListElement { name: "blah3" textEnabled:false } } Component { id: mylistDelegate Text { id: mylistDelegateText text: name color: textEnabled?"red":"black" MouseArea { anchors.fill:parent; onClicked: { mylistModel.setProperty(index, "textEnabled", !textEnabled); } } } } ListView { id: mylistView model: mylistModel delegate: mylistDelegate width:100; height:100 } } 
+5
source

Try this code: -

  for (var i = 0; i < mylistView.count; i ++) { // this will get list item at index i console.log(mylistView.contentItem.children[i]); // lets set it height to 100 mylistView.contentItem.children[i].height=100; } 

Hope this helps, cheers !!! @navi

+2
source

Source: https://habr.com/ru/post/911133/


All Articles