Search code examples
pythonpython-3.xpyside2

PySide2 - change table header background color


What I have now is default QTableWidget. I only changed background color for rows with even indexes. I want to do the same for table headers.

enter image description here

What I tried - self.horizontalHeaderItem(...).setBackgroundColor(QColor(...)) and self.horizontalHeaderItem(...).setBackground(QBrush(...)) - fail.

What I tried next - self.horizontalHeader().setStyleSheet("::section {" "background-color: lightblue; }") - I managed to change background color. The problems are (1) I don't quite understand what this code actually is since I can't find it in the PySide2 documentation, (2) the code changes not only background but many header appearance features.

How can I change only header background? Or more generally - how to tune table header appearance in PySide2?

enter image description here


Solution

  • Here I post what I learned in my quest for the answer - 2 possible solutions.

    I guess the problem originates from some tangled mixture of notImplemented, notDocumented, notExplained issues with PySide2. I hope the situation will change for the better in the future. Now to the answer.

    The problem may be solved like this (and may not):

    plt = QPalette()
    plt.setColor(QPalette.Button, QColor(128, 0, 0))
    my_table_widget.horizontalHeader().setPalette(plt)
    

    QPalette controls colors of widgets. But there is another layer of appearance control - style. I use PySide2 on Win10x64 so default style is windowsvista with 3 styles available in total: fusion, windows, windowsvista. Windowsvista style ignores most of the palette colors. So for this approach to work one should change the style of the whole application (or some widgets only?):

    app.setStyle(QStyleFactory.create('fusion'))
    

    Another solution I came up with is (preferable for me):

    my_table_widget.horizontalHeader().setStyleSheet('''
        ::section {
            background-color: lightgray;
            border-style: flat;
            padding: 0px 5px;
            }''')
    

    together with:

    my_table_widget.horizontalHeader().setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter)
    

    I guess this is a style sheet to tune button appearance. I don't quite understand the meaning of section word. Moreover, to use this approach one should use google and Qt5 documentation. How my table looks with the second solution applied:

    enter image description here