PDA

View Full Version : Change the ListModel dynamically



stereoMatching
6th July 2013, 06:22
import QtQuick 2.1
import QtQuick.Controls 1.0

Rectangle {
id: root
width: 500
height: 500

state: "one"

ListModel{
id: one
}

ListModel{
id: two
}

function changeModel(){
if(state == "one"){
one.append({"source": "aaa"})
return one
}else{
two.append({"source": "bbb"})
return two
}
}

Row{
Button{
id: buttonOne

text: "One"

onClicked: {
root.state = "one"
}
}

Button{
id: buttonTwo

text: "Two"

onClicked: {
root.state = "two"
}
}

TableView{
id: tableView
model: changeModel()

TableViewColumn {
title: "image"

delegate: Text{ text: tableView.model.get(styleData.row).source }
}
}
}

}


When I click the “Two” button, there are always an error message

qrc:/main.qml:59: TypeError: Cannot read property ‘source’ of undefined

How could I change the model dynamically?What kind of mistake I make?Thanks

stereoMatching
6th July 2013, 21:11
Got the answer from here
http://qt-project.org/forums/viewthread/29653/



The reason is that you change your underlaying model of the TableView and both are not of the same length.
Since you use .get(styleData.row) all the delegates visible in the table refer to a specific element on index (row number) in you model.
If you change the model, each delegate will try to get its data again, but the number of items of the other model is different, and if the number of items is less than the items that are visible, some of the items will fail to get its data, those rows will dissappear but give an error.
If you use:

#
delegate: Text{ text: styleData.value }

instead, then it works, without errors, but then you cannot have multiple properties in the same ListElement.

Hope it helps.