代码之家  ›  专栏  ›  技术社区  ›  DELI

如何在QML中修改TableView数据?

  •  0
  • DELI  · 技术社区  · 2 年前

    我不知道如何动态修改模型中的数据绑定。这是QT中的官方示例文档。 我在其中添加了一个按钮,并试图通过object修改name的数据,但失败了。

    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
          }
        }
      }
    }
    

    问题是,当按钮被触发时,修改后的行值无法生效。

    我试图查看帮助文档或在搜索引擎中搜索答案,但我得到的信息太少,所以我不得不在这里向有经验的程序员寻求帮助。

    1 回复  |  直到 2 年前
        1
  •  0
  •   eyllanesc Yonghwan Shin    2 年前

    您必须使用 setData 方法:

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