PYQT:水平和垂直 Headers

PYQT: Horizontal and Vertical Headers

有谁知道如何向 QTableView 添加垂直和水平 headers?我已经为此工作了几个小时,但我似乎无法弄清楚。 当前结果:

但是,我正在尝试制作这个:(抱歉,我在 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 添加到 model-class。我能够使垂直 headers 工作,但不能使水平工作。这是结果:

header 数据是每个 column/row,因此您必须 return 特定部分的 header,而不是所有 3 个。 str("X", "Y", "Z") str 的使用无效,您只需要 return 由 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)