Setting header data in QTableView

Rodrigo de Salvo Braz rodrigobraz at gmail.com
Mon Feb 8 03:15:33 GMT 2021


Awesome, thanks, that's exactly what I needed to know.

Rodrigo

On Sun, Feb 7, 2021 at 8:31 PM Maurizio Berti <maurizio.berti at gmail.com>
wrote:

> Il giorno sab 6 feb 2021 alle ore 10:46 Rodrigo de Salvo Braz <
> rodrigobraz at gmail.com> ha scritto:
>
>> 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?
>>
>
> If you simply try to print the result of your `setHeaderData()` calls,
> you'll see that the returned value is always False.
>
> By default abstract item models do not implement anything on their basic
> methods, especially when trying to set data and properties on the model
> itself. Those methods are implemented in models that are *not* abstract and
> allow data writing (such as QStandardModelItem or, in your case,
> QSqlQueryModel and all its inherited classes which are reported in your
> link). The same would happen, in fact, for setData(), which makes sense:
> being an abstract model, it's up to you to actually set the data and return
> whether if the setting actually occurred or not.
>
> Methods like setHeaderData() will always return False (meaning that the
> data has not been set) unless they're actually implemented in order to
> return True.
>
> class TableModel(QtCore.QAbstractTableModel):
>     def __init__(self):
>         super().__init__()
>         self.headers = []
>         for i in range(4):
>             self.setHeaderData(i, Qt.Horizontal, "Column " + str(i))
>
>     def setHeaderData(self, section, orientation, value,
> role=QtCore.Qt.EditRole):
>         if (orientation == QtCore.Qt.Horizontal and
>             0 <= section < self.columnCount() and role ==
> QtCore.Qt.EditRole):
>                 while len(self.headers) < section + 1:
>                     self.headers.append(None)
>                 self.headers[section] = value
>                 self.headerDataChanged.emit(orientation, section, section)
>                 return True
>         return False
>
> --
> È difficile avere una convinzione precisa quando si parla delle ragioni
> del cuore. - "Sostiene Pereira", Antonio Tabucchi
> http://www.jidesk.net
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20210208/b91a7f8a/attachment.htm>


More information about the PyQt mailing list