Setting header data in QTableView

Colin McPhail colin.mcphail at mac.com
Sun Feb 7 10:16:44 GMT 2021



> On 6 Feb 2021, at 09:46, Rodrigo de Salvo Braz <rodrigobraz at gmail.com> wrote:
> 
> Hi,
> 
> Qt's documentation says <https://doc.qt.io/qtforpython-5.12/overviews/sql-presenting.html> one can use setHeaderData to set column headers.
> 
> However, I used it in the simple example below and it has no effect. Why not?
> 
> Note: I've used headerData to return column names directly and it works. However, I am curious why setHeaderData doesn't work in this example.
> 
> Thanks,
> 
> Rodrigo
> PS: please let me know if this list should be used only for questions more specific about PyQt as opposed to Qt.
> import sys
> 
> from PyQt5 import QtCore
> from PyQt5.QtCore import Qt
> from PyQt5.QtWidgets import QVBoxLayout, QWidget, QApplication, QMainWindow, QTableView
> 
> 
> class TableModel(QtCore.QAbstractTableModel):
>     def __init__(self):
>         super().__init__()
>         for i in range(4):
>             self.setHeaderData(i, Qt.Horizontal, "Column " + str(i))
> 
>     def data(self, index, role=None):
>         if role == Qt.DisplayRole:
>             return 42
> 
>     def rowCount(self, index):
>         return 3
> 
>     def columnCount(self, index):
>         return 4
> 
> 
> class MainWindow(QMainWindow):
>     def __init__(self):
>         super().__init__()
> 
>         l = QVBoxLayout()
> 
>         self.table = QTableView()
> 
>         self.model = TableModel()
>         self.table.setModel(self.model)
> 
>         l.addWidget(self.table)
> 
>         w = QWidget()
>         w.setLayout(l)
>         self.setCentralWidget(w)
> 
> 
> app = QApplication(sys.argv)
> w = MainWindow()
> w.show()
> app.exec_()
> 
Hi,

I believe that in class TableModel instead of calling the inherited setHeaderData() method you must provide your own implementation of it. Perhaps something like

    def headerData(self, section, orientation, role):
        if orientation == Qt.Vertical:
            return None
        elif role == Qt.DisplayRole:
            return "Column " + str(section)
        else:
            return None

Regards,
Colin

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20210207/f8c33184/attachment.htm>


More information about the PyQt mailing list