Does anyone know how to add vertical and horizontal headers to a QTableView? I have been working on this for several hours now, and I can't seem to figure it out.
Current Result:

However, I am trying to produce this: (Sorry, I did it in excel -- however, I hope you get the idea).

Here is my code:
from PyQt4 import QtCore, QtGui, uic
import sys
try:
from PyQt4.QtCore import QString
except ImportError:
QString = str
SYSTEM=0
class inovaTableModel( QtCore.QAbstractTableModel ):
def __init__(self, data = [[]], headers=[], parent=None):
QtCore.QAbstractTableModel.__init__(self, parent )
self.__data = data
self.__headers = headers
def rowCount(self, parent):
return len(self.__data)
def columnCount(self, parent):
return len(self.__data[0])
def flags(self, index):
return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def data(self, index, role):
if role == QtCore.Qt.EditRole:
row = index.row( )
column = index.column( )
return self.__data[row][column]
if role == QtCore.Qt.ToolTipRole:
row = index.row( )
column = index.column( )
return self.__data[row][column]
if role == QtCore.Qt.DisplayRole:
row = index.row( )
column = index.column( )
return self.__data[row][column]
def setData(self, index, value, role = QtCore.Qt.EditRole):
if role ==QtCore.Qt.EditRole:
row = index.row()
column = index.column()
self.dataChanged.emit(index, index)
return self.__data[row][column]
def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return QString("X","Y","Z")
if orientation == QtCore.Qt.Vertical:
return QString("List ") + QString(section)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
app.setStyle( "plastique" )
data = ["one", "two", "three",]
tableData_alpha = [
["5","1"],
["10", "3"],
]
headers = ["Y", "X", "Z"]
model = inovaTableModel(tableData_alpha)
tableView = QtGui.QTableView()
tableView.show()
tableView.setModel(model)
sys.exit(app.exec_())
I added headerData to the model-class. I am able to get the vertical headers to work, but not the Horizontal. Here is the Result:

The header data is per column/row, so you have to return the header for specific section, rather than all 3. The
str("X", "Y", "Z")is not valid use ofstr, you need to return just the one identified by value ofsection: