Change the ListModel dynamically

  • @
    import QtQuick 2.1
    import QtQuick.Controls 1.0

    Rectangle {
    id: root
    width: 500
    height: 500

    state: "one"
        id: one
        id: two
    function changeModel(){
        if(state == "one"){
            one.append({"source": "aaa"})
            return one
            two.append({"source": "bbb"})
            return two
            id: buttonOne
            text: "One"
            onClicked: {
                root.state = "one"
            id: buttonTwo
            text: "Two"
            onClicked: {
                root.state = "two"
            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

  • 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.

  • Thanks for your help:).Do we have a more flexible way to switch between different models?

    Solution one :
    Design a intermediate models(called C) with several properties
    when I switch the model, I could clear the data of C
    and copy the data of different models(A or B) to C

    Solution two :
    Use Loader to load the view, when the model change
    destroy the old table and load a new table

    Do you have easier solutions?Thanks a lot

Log in to reply