如何在Qt5中更改TableView标题的颜色(背景,文本)?

alr*_*alr 7 qt qml qt5 qtquick2

TableView在Qt5中用于我的应用程序.可以更改此表的行的颜色(背景,文本和替代),但没有更改标题(标题)颜色的选项.

怎么做?

Mit*_*tch 19

它有选择:headerDelegate.您可以使用TableView或中的一个TableViewStyle.这是一个headerDelegateBase样式中获取实现的示例:

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"
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

截图

您可能已经注意到,标题末尾有一个"颜色故障"(见上面的截图).这是因为,默认情况下,该backgroundColor属性设置为white.更改它以匹配标题颜色可以解决问题,即将以下行添加到您的TableViewStyle实现中:

backgroundColor : "lightsteelblue"
Run Code Online (Sandbox Code Playgroud)