Try with:
MAX_HEIGHT = 4096 # Arbitrary value
class HeaderView(QHeaderView):
def __init__(self, parent=None):
super().__init__(Qt.Horizontal, parent=parent)
self.setStyleSheet(
"QHeaderView::section{background-color: #ffffff; "
"font-weight: bold; "
"padding-left: 2px; "
"color: #3467ba; "
"border:0px; "
"border-left: 1px solid #ababab; "
"border-bottom: 1px solid gray;}"
)
self.setStretchLastSection(True)
self.setDefaultAlignment(Qt.AlignCenter | Qt.Alignment(Qt.TextWordWrap))
def sectionSizeFromContents(self, logicalIndex):
text = self.model().headerData(logicalIndex, self.orientation(), Qt.DisplayRole)
alignment = self.defaultAlignment()
metrics = QFontMetrics(self.fontMetrics())
width = metrics.boundingRect(QRect(), alignment, text).width()
heights = []
for i in range(self.count()):
text = self.model().headerData(i, self.orientation(), Qt.DisplayRole)
size = self.sectionSize(i)
rect = QRect(0, 0, size, MAX_HEIGHT)
heights.append(metrics.boundingRect(rect, alignment, text).height())
height = sorted(heights)[-1]
return QSize(width, height)