Home > Net >  How to modify TableView data in QML?
How to modify TableView data in QML?

Time:06-27

I don't know how to dynamically modify the data bound in the model. This is the official example document in QT. I added a button to it and tried to modify the data of name through object, but failed.

ApplicationWindow {
  id: window
  width: 300
  height: 300
  visible: true

  //I added this button
  Button {
    x:179
    y:235
    text: "Button"
    z: 1
    onClicked: {
      //There's no use here!
      t1.model.rows[0].name = "cat2"
      console.log(t1)
    }
  }
  // Button End

  TableView {
    id: t1
    anchors.fill: parent
    columnSpacing: 1
    rowSpacing: 1
    clip: true

    model: TableModel {
      TableModelColumn {
        display: "name"
      }
      TableModelColumn {
        display: "color"
      }

      rows: [{
          "name": "cat",
          "color": "black"
        }, {
          "name": "dog",
          "color": "brown"
        }, {
          "name": "bird",
          "color": "white"
        }]
    }

    delegate: Rectangle {
      implicitWidth: 100
      implicitHeight: 50
      border.width: 1

      Text {
        text: display
        anchors.centerIn: parent
      }
    }
  }
}

The problem is that when the button is triggered, the modified row value fails to take effect.

I tried to check the help document or search for answers in the search engine, but I got so little information that I had to ask experienced programmers for help here.

CodePudding user response:

You have to use the setData method:

onClicked: {
    var ix = t1.model.index(0, 0);
    if (t1.model.setData(ix, "display", "cat2"))
        console.log("success");
    else
        console.log("failed");
}
  • Related