有谁知道如何向QTableView添加垂直和水平标题?我现在已经工作了好几个小时了,我似乎无法弄明白。 目前的结果:
然而,我试图产生这个:(对不起,我是在excel中做到的 - 但是,我希望你能得到这个想法)。
这是我的代码:
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_())
我将headerData添加到了模型类中。我能够使垂直标题工作,但不能使用Horizontal。结果如下:
答案 0 :(得分:2)
标题数据是每列/行,因此您必须返回特定部分的标题,而不是全部3. str("X", "Y", "Z")
无效使用str
,您只需要返回由section
:
def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return ["X", "Y", "Z"][section]
if orientation == QtCore.Qt.Vertical:
return QString("List ") + QString(section)