QT开发中文网

qml 点击按钮,获取tableview选中行数据

要获取TableView的选中行数据,可以使用TableView的selectionModel属性和model属性结合使用。selectionModel用于跟踪当前选择项,而model用于存储数据。

以下是一个示例代码:

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    TableView {
        id: tableView
        anchors.fill: parent
        model: ListModel {
            ListElement { name: "John"; age: 25 }
            ListElement { name: "Mary"; age: 30 }
            ListElement { name: "Tom"; age: 35 }
            ListElement { name: "Lucy"; age: 40 }
        }

        TableViewColumn {
            role: "name"
            title: "Name"
            width: 200
        }

        TableViewColumn {
            role: "age"
            title: "Age"
            width: 100
        }
    }

    Button {
        text: "Print Selected Row"
        onClicked: {
            var selectedRow = tableView.selectionModel.currentIndex.row
            console.log(tableView.model.get(selectedRow))
        }
    }
}

在这个例子中,我们首先创建了一个包含数据和列定义的TableView。然后,我们添加了一个按钮,当单击该按钮时,它将输出选中行的数据。

在按钮的onClick事件处理程序中,我们首先使用tableView.selectionModel.currentIndex.row获取当前选中行的索引,然后再使用tableView.model.get(selectedRow)获取相应的数据。这里的model是一个ListModel,因此我们可以使用其get()方法来获取指定索引处的元素。

这样,当用户单击TableView中的某一行时,就可以在控制台中看到相应的数据了。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=813

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?