我在Qt5应用程序中使用TableView
。可以更改此表格的行的颜色(背景,文本和交替),但是没有更改标题(标题)颜色的选项。
如何更改标题颜色?
有以下选项可供选择:headerDelegate
。您可以使用TableView
或TableViewStyle
中的任意一个。下面是一个示例,其中包含从Base
样式中获取的headerDelegate
实现:
import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.2
Window {
id: win
width: 360
height: 360
visible: true
ListModel {
id: libraryModel
ListElement {
title: "A Masterpiece"
author: "Gabriel"
}
ListElement {
title: "Brilliance"
author: "Jens"
}
ListElement {
title: "Outstanding"
author: "Frederik"
}
}
TableView {
TableViewColumn {
role: "title"
title: "Title"
width: 100
}
TableViewColumn {
role: "author"
title: "Author"
width: 200
}
model: libraryModel
style: TableViewStyle {
headerDelegate: Rectangle {
height: textItem.implicitHeight * 1.2
width: textItem.implicitWidth
color: "lightsteelblue"
Text {
id: textItem
anchors.fill: parent
verticalAlignment: Text.AlignVCenter
horizontalAlignment: styleData.textAlignment
anchors.leftMargin: 12
text: styleData.value
elide: Text.ElideRight
color: textColor
renderType: Text.NativeRendering
}
Rectangle {
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.bottomMargin: 1
anchors.topMargin: 1
width: 1
color: "#ccc"
}
}
}
}
}
您可能已经注意到,标题的末尾有一个“颜色故障”(请参见上面的屏幕截图)。这是因为,默认情况下,backgroundColor
属性设置为 white
。将其更改为与标题颜色相匹配即可解决此问题,即在您的 TableViewStyle
实现中添加以下行:
backgroundColor : "lightsteelblue"
Mitch的例子是一个很好的基础,但在我这里并不完全好用。调整大小的线没有正确显示,而且我还想要底线。对我来说这个更好用(在Qt5.12上测试过):
SystemPalette { id: myPalette; }
style: TableViewStyle {
backgroundColor: myPalette.base
headerDelegate: Item {
height: textLine.implicitHeight * 1.2 + 1
Rectangle {
color: myPalette.light
height: textLine.implicitHeight * 1.2
Text {
id: textLine
anchors.fill: parent
color: myPalette.text
verticalAlignment: Text.AlignVCenter
horizontalAlignment: styleData.textAlignment
text: styleData.value
anchors.leftMargin: 8
elide: Text.ElideRight
renderType: Text.NativeRendering
}
}
Rectangle {
anchors.left: parent.left
anchors.right: parent.right
height: 1
y: textLine.implicitHeight * 1.2
color: myPalette.mid
}
Rectangle {
anchors.top: parent.top
anchors.bottom: parent.bottom
width: 1
anchors.right: parent.right
color: myPalette.mid
}
}
}
我也依赖于调色板。这样做的额外好处是可以与 macOS 的深色模式和亮色模式一起使用。
实际上,mid
在深色模式下有点暗... 但在 macOS 中,我发现许多对比度都有点弱,所以也许还好,你需要自己试试看。不幸的是,Qt 的调色板文档再次缺乏任何关于边框颜色的提示。也许,它完全缺失了。
headerDelegate
意味着它们会丢失,所以你需要自己实现它们。 - Mitch