Important: Please read the Qt Code of Conduct -

QHeaderView paintSection Problem

  • Hi Forum,

    Im trying to change the background color of the header im using for my tableview, i am subclassing QHeaderView because the bg-color for the header will vary based on certain parameters. below is the code:

    from PyQt4 import QtCore, QtGui

    class CustomHeader(QtGui.QHeaderView):

    def __init__(self, orientation, parent):
        super(CustomHeader, self).__init__(orientation, parent)
    def paintSection(self, painter, rect, section):
        option = QtGui.QStyleOptionHeader()
        option.textAlignment = QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter
        option.text = "Date %d"%section
        option.rect = rect
        p = option.palette
        p.setBrush(p.Button,, option, painter)

    class CustomController(QtCore.QAbstractTableModel):

    def __init__(self, parent=None):
        super(CustomController, self).__init__(parent)
    def rowCount(self, parent=QtCore.QModelIndex()):
        return 10
    def columnCount(self, parent=QtCore.QModelIndex()):
        return 10
    def data(self, index, role):
        if role == QtCore.Qt.DisplayRole:
            if index.column() == 0:
                return "Artist xx"
                return None
        if role == QtCore.Qt.TextAlignmentRole:
            return QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter
        return None

    if name == "main":
    app = QtGui.QApplication([])
    view = QtGui.QTableView()
    c_header = CustomHeader(QtCore.Qt.Horizontal, view)
    model = CustomController(view)

    the issue is this works only if the application's style is set to something other than native.
    i'm on a mac book pro using Qt version 4.8.5. is this a bug which i've already reported at if yes is there a work around for this issue.?

Log in to reply