如何获取QTableVi的当前列及其排序方向

2024-09-29 04:20:04 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

此代码创建一个QTableView。单击列将显示指示列排序方向的箭头。单击tableView的项本身会打印出单击的索引。单击tableView项时,我想知道三列(标题)中的哪一列(显示箭头的列)以及排序箭头指向的方向:向上还是向下。如何做到这一点?在

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class Model(QtCore.QAbstractTableModel):
    def __init__(self):
        QtCore.QAbstractTableModel.__init__(self)
        self.items = [[1, 'one', 'ONE'], [2, 'two', 'TWO'], [3, 'three', 'THREE']]

    def rowCount(self, parent=QtCore.QModelIndex()):
        return 3 
    def columnCount(self, parent=QtCore.QModelIndex()):
        return 3

    def data(self, index, role):
        if not index.isValid(): return 

        if role in [QtCore.Qt.DisplayRole, QtCore.Qt.EditRole]:
            return self.items[index.row()][index.column()]

def onClick(index):
    print 'clicked index:  %s'%index

def sortIndicatorChanged(column=None, sortOrder=None):
    print 'sortIndicatorChanged: column: %s, sortOrder: %s'%(column, sortOrder)

tableModel=Model()
tableView=QtGui.QTableView() 
tableView.setModel(tableModel)
tableView.setSortingEnabled(True)
tableView.clicked.connect(onClick)
tableView.horizontalHeader().sortIndicatorChanged.connect(sortIndicatorChanged)
tableView.show()

app.exec_()

Tags: selfappindexreturn排序defcolumn箭头