QML ListModel: remove: indices out of range
-
When i try to delete from listmodel i get an error like this;
--> QML ListModel: remove: indices [2 - 3] out of range [0 - 1]
The purpose of the code is to create a multiselect-combobox and output the selections made with this combobox. (This is a lesson assignment. And ı have to use combobox and listview.)import QtQuick 2.9 import QtQuick.Window 2.2 import QtQuick.Controls 2.2 ApplicationWindow { id: applicationWindow visible: true; width: 640 height: 480 ListModel { id: listmodelId } ComboBox { id: comboboxId width: parent.width / 2 height: 50 displayText: "SELECT" model: ListModel { ListElement { name: "One"; turk: "bir"; fill: "red"} ListElement { name: "Two"; turk: "iki"; fill: "green"} ListElement { name: "Three"; turk: "uc" ; fill: "blue"} ListElement { name: "Four"; turk: "dort" ; fill: "pink"} ListElement { name: "Five"; turk: "bes" ; fill: "yellow"} ListElement { name: "Six"; turk: "alti" ; fill: "orange"} ListElement { name: "Seven"; turk: "yedi" ; fill: "purple"} } delegate: Item { width: parent.width height: 50 Row { spacing: 5 anchors.fill: parent anchors.margins: 5 CheckDelegate { id: checkboxId height: parent.height width: height onCheckStateChanged: { if (checkState === Qt.Checked){ console.log("index Checked= "+index) listmodelId.append({ "name": name, "turk":turk, "fill": fill }) } if(checkState === Qt.Unchecked) { console.log("index Unchecked= "+index) listmodelId.remove(index); } } } Label { text: name width: parent.width - checkboxId.width height: parent.height verticalAlignment: Qt.AlignVCenter horizontalAlignment: Qt.AlignHCenter } } } } ListView { id: listviewId width: parent.width / 2 height: parent.height anchors.left: comboboxId.right model: listmodelId delegate: Item { height: 50 width: parent.width Rectangle { anchors.fill: parent color: fill Text { anchors.centerIn: parent text: name+" "+turk } Button{ text: "delete" onClicked:{ listmodelId.remove(index) } } } } onCountChanged: console.log(count) } }```
-
@hcaslan I haven't looked at this in detail but I think it might be because the
index
you are using to pass toremove
is the model index for the combo box model, but you are callingremove
on thelistmodelId
model, and this model is not directly related to what is being shown in the combo. -
If the requirement is, as you say, simply to output the selections, the simplest way might be to clear the output list and rebuild it every time a selection is changed. Then you just need to loop over the combo list and add the items that are selected.
I have noticed that you are not storing the check state in your combo model. You would need to do this to implement what I just suggested, but in any case I think you can't rely on the delegate to store the checked state. You might get away with it here, but in general, and especially if you had a longer list in your combo, delegates can get "recycled" in the view so you cannot rely on them holding any state.