TableView {
id: testTable
rowSpacing: 0
columnSpacing: 8
clip: true
anchors.topMargin: 2
boundsBehavior: Flickable.OvershootBounds
columnWidthProvider: function(column) {
if(column === 0) return 50;
else if(column === 1) return 580;
else return 60;
}
model: tableModel
delegate: Rectangle {
id: cellContainer
implicitWidth: 100
implicitHeight: 42
Text {
anchors.fill: parent
verticalAlignment: Qt.AlignVCenter
horizontalAlignment: column === 1 ? Qt.AlignLeft : Qt.AlignHCenter
font.family: outfitRegular.name
font.pixelSize: 14
text: {
var col = model.columnNo
if(col === 0)
return model.index
else if(col === 1)
return model.name
else
return model.status
}
}
MouseArea {
id: mouse
anchors.fill: parent
onClicked: {
console.log(model.index)
}
}
}
}
我尝试在 mouseArea 的 onClick 方法中为委托着色,但正如预期的那样,它只更改单元格颜色,而不更改整行的颜色。我想知道我应该做什么来实现这一目标。 我在堆栈溢出上找到了较旧的代码,但它们都不适用于较新版本的 TableView。
我是 QML 新手,任何与此相关的意见都会有所帮助。
只是为了说明这个想法:
import QtQuick
import Qt.labs.qmlmodels
Window {
id: window
visible: true
width: 600
height: 400
title: "Typing trainer"
TableView {
id: table
anchors.fill: parent
columnSpacing: 1
rowSpacing: 1
clip: true
property int selectedRow: -1
model: TableModel {
TableModelColumn { display: "col1" }
TableModelColumn { display: "col2" }
TableModelColumn { display: "col3" }
rows: [
{
"col1": "value1",
"col2": "value2",
"col3": "value3",
},
{
"col1": "value4",
"col2": "value5",
"col3": "value6",
},
{
"col1": "value7",
"col2": "value8",
"col3": "value9",
}
]
}
delegate: Rectangle {
implicitWidth: 100
implicitHeight: 40
border.width: 1
border.color: "#999"
color: row === table.selectedRow ? "lightblue" : "white"
Text {
text: display
anchors.centerIn: parent
}
}
selectionBehavior: TableView.SelectRows
selectionModel: ItemSelectionModel {
onCurrentChanged: {
table.selectedRow = currentIndex.row;
}
}
}
}
或者以更通用的方式您可以设置
required property bool selected
required property bool current
如here所述,您还可以使用SelectionRectangle等