0
votes

When I first set TableView column and List Model. it display normal

But when I change column number by remove all column and add column and I also update my List Model. TableView is become empty It just show 2 column I add and don't show data.

I'm using Qt 5.7 and using TableView in QtQuick.Controls 1.4 Here is my code:

TableView {
    id: tbl
    width: 400
    height: 300
    model: lst
}

Component {
    id: columnComponent
    TableViewColumn {
        width: 50
    }
}

ListModel {
    id: lst
}

Button {
    text: "Click me"
    anchors.top: tbl.bottom

    onClicked: {
        for(var i = tbl.columnCount-1; i>=0; i--) {
            tbl.removeColumn(i)
        }
        tbl.addColumn(columnComponent.createObject(tbl,{ role: "1"}))
        tbl.addColumn(columnComponent.createObject(tbl,{ role: "2"}))
        tbl.addColumn(columnComponent.createObject(tbl,{ role: "3"}))

        lst.clear()
        var element = {}
        element["1"] = "a"
        element["2"] = "a"
        element["3"] = "a"
        lst.append(element)

        tbl.model = lst
    }
}

Button {
    text: "Click me 2"
    anchors.left: tbl.right

    onClicked: {
        for(var i = tbl.columnCount-1; i>=0; i--) {
            tbl.removeColumn(0)
        }
        tbl.addColumn(columnComponent.createObject(tbl,{ role: "a"}))
        tbl.addColumn(columnComponent.createObject(tbl,{ role: "b"}))

        lst.clear()
        var element = {}
        element["a"] = "b"
        element["b"] = "b"
        lst.append(element)

        tbl.model = lst
    }
}
1

1 Answers

0
votes

Apparently you need to set to temporarily detach the model from the TableView. Add a line to each of your onClicked slots:

onClicked: {
    tbl.model = undefined    // add this line, temporarily detach tbl.model

    for(var i = tbl.columnCount-1; i>=0; i--) {
        tbl.removeColumn(i)
    }

    // ... 
    // code omitted for brevity 
    // ...

    tbl.model = lst   //  reset the model
}

Credits to roigallego for the solution from forum.qt.io.