How to change the color (background, text) of header of TableView in Qt5?

11,778

There are options for it: headerDelegate. You can use the one in TableView or TableViewStyle. Here's an example with a headerDelegate implementation taken from the Base style:

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

screenshot

As you may have noticed, there is a "colour glitch" at the end of the header (see screenshot above). That is because, by default, the backgroundColor property is set to white. Changing it to match the header color solves the issue, i.e. add the following line to your TableViewStyle implementation:

backgroundColor : "lightsteelblue"
Share:
11,778
alr
Author by

alr

Updated on August 03, 2022

Comments

  • alr
    alr almost 2 years

    I use TableView for my application in Qt5. It's possible to change color (background, text and alternate) of rows of this table, but there is no options for changing color of headers (titles).

    How to do that?