简体   繁体   中英

QML update the property of Item inside the ListView

Item {

Component.onComplete: {
    for (var i=0;i < 10;i++) {
        myModel.append({"myTxt": "SomeThing"+i});
    }
}

ListModel {
    id: myModel
}

ListView {
    id: listView
    width: parent.width
    height: parent.height
    model: myModel
    delegate: Rectangle {
        property string propItemState: 0;
        
        MyListItem {
            id: test
            itemText: myText
            itemState: propItemState;
        }
    }
}
}

I want to update the propItemState once the list is displayed.
For that, I have tried the below method but am getting an undefined error.
I am calling this method once the list model is updated.

function updateListItems() {
    for (var index=0;index < listView.count;index++) {
        console.log("propItemState: "+listView.contentItem.children[index].propItemState);
        listView.contentItem.children[index].propItemState = 2;
    }
}

You can bind propItemState to something outside of your delegate. Or you can add signal handler ( Connections ), which listens to your model (for example; or to some another class) and changes state when your conditions met.

Example:

Item {
    Component.onComplete: {
        for (var i=0;i < 10;i++) {
            myModel.append({"myTxt": "SomeThing"+i});
        }

        internal.state = "1";
    }

    ListModel {
        id: myModel
    }

    QtObject {
        id: internal
        property string state: "0"
    }

    ListView {
        id: listView
        width: parent.width
        height: parent.height
        model: myModel
        delegate: Rectangle {
            property string propItemState: internal.state

            MyListItem {
                id: test
                itemText: myText
                itemState: propItemState;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM