1

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()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Spencer
  • 1,931
  • 1
  • 21
  • 44

1 Answers1

5

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Wow so you need to call the header of the model of the header! I was trying to get to the data directly, which of course did not work. – Spencer Dec 04 '19 at 01:48