Search code examples
pythonpyqtqheaderview

Get header section text in QHeaderView


I am subclassing a QHeaderView within a QTableWidget to provide custom functionality for hiding/showing sections. Is there a way to get the text of a section from within the header view? I know I can do this from within the scope of the table, but that is not what I am trying to do.

I realize the data is stored internally in a model, however the following test just returns "None":

self.model().index(0,0).data()

Solution

  • You can use the model assigned to the QHeaderView and get the text using the headerData() method:

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    
    class HeaderView(QtWidgets.QHeaderView):
        def text(self, section):
            if isinstance(self.model(), QtCore.QAbstractItemModel):
                return self.model().headerData(section, self.orientation())
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
    
        w = QtWidgets.QTableWidget(10, 4)
        w.setHorizontalHeaderLabels(
            ["section-{}".format(i) for i in range(w.columnCount())]
        )
    
        horizontal_headerview = HeaderView(QtCore.Qt.Horizontal, w)
        w.setHorizontalHeader(horizontal_headerview)
    
        print(horizontal_headerview.text(1))
    
        vertical_headerview = HeaderView(QtCore.Qt.Vertical, w)
        w.setVerticalHeader(vertical_headerview)
    
        print(vertical_headerview.text(2))
    
        w.show()
    
        sys.exit(app.exec_())