Опишу поподробней задачу. Нас интересует вертикальный заголовок QTableView - нужна простая нумерация строк по порядку, вдобавок она должна оставаться правильной при включенной сортировке по заголовку столбца. Т.е. всегда 1,2,3,4,5….100… Если делаю так как в коде ниже, получается черт знает что, а не нумерация по порядку. Я хотел создавать вертикальный заголовок в цикле уже после формирования модели в TableView, методом setHeaderData(), но насколько я понял у QAbstractTableModel этот метод не организован (нужно создавать самому), чтото типа:
def setHeaderData(self, section, orientation, value, role):
if …….:
.
.
.
model.headerDataChanged.emit(orientation, section, section)
return True
else:
return False
Вот с наполнением функции у меня полная непонятка.
В интернете не нашел ни одного примера реализации этого метода.
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
class MyWindow(QtGui.QWidget):
def __init__(self, *args):
QtGui.QWidget.__init__(self, *args)
table = self.createTable()
layout = QtGui.QVBoxLayout()
layout.addWidget(table)
self.setLayout(layout)
def createTable(self):
tv = QtGui.QTableView()
tm = MyTableModel(self)
# set the proxy model
pm = QtGui.QSortFilterProxyModel(self)
pm.setSourceModel(tm)
tv.setModel(pm)
tv.setMinimumSize(400, 300)
# show vertical header
tv.verticalHeader().setVisible(True)
# Сортировка по щелчку на заголовке столбца
tv.setSortingEnabled(True)
tv.sortByColumn(0, QtCore.Qt.AscendingOrder)
return tv
class MyTableModel(QtCore.QAbstractTableModel):
def __init__(self, parent=None, *args):
QtCore.QAbstractTableModel.__init__(self, parent, *args)
self.colLabels = ['Col1', 'Col2', 'Col3', 'Col4', 'Col5']
self.cached = [
['89','cell12','cell13','cell14','cell15',],
['34','cell22','cell23','cell24','cell25',],
['56','cell32','cell33','cell34','cell35',],
['18','cell42','cell43','cell44','cell45',],
['22','cell52','cell53','cell54','cell55',],
['44','cell62','cell63','cell64','cell65',],
['19','cell72','cell73','cell74','cell75',],
['76','cell82','cell83','cell84','cell85',],
]
def rowCount(self, parent):
return len(self.cached)
def columnCount(self, parent):
return len(self.colLabels)
def data(self, index, role):
if not index.isValid():
return QtCore.QVariant()
elif role != QtCore.Qt.DisplayRole and role != QtCore.Qt.EditRole:
return QtCore.QVariant()
value = ''
if role == QtCore.Qt.DisplayRole:
row = index.row()
col = index.column()
value = self.cached[row][col]
return QtCore.QVariant(value)
def headerData(self, section, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return QtCore.QVariant(self.colLabels[section])
#заголовки строк
if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
return QtCore.QVariant("%s" % str(section + 1))
return QtCore.QVariant()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())