Tips

Grosse Tabellen

import operator
import sys
from PyQt4 import QtCore, QtGui


def main():
    app = QtGui.QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

    
class MyWindow(QtGui.QWidget):

    tabledata = [[1,102,3],[24,15,-6],[7,8,9]]
    tableheader = ['a','b','c']
    
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)

        # create table
        table = self.createTable()
         
        # layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(table)
        self.setLayout(layout)

        
    def createTable(self):
        # create the view
        tv = QtGui.QTableView()

        # set the table model
        tv.setModel(MyTableModel(self.tabledata, self.tableheader, self))

        # set the minimum size
        tv.setMinimumSize(400, 300)

        # hide vertical header
        tv.verticalHeader().setVisible(False)

        # enable sorting
        tv.setSortingEnabled(True)

        return tv


    
class MyTableModel(QtCore.QAbstractTableModel):
    
    def __init__(self, data, header, parent=None, *args):
        QtCore.QAbstractTableModel.__init__(self, parent, *args)
        self.arraydata = data
        self.headerdata = header

        
    def rowCount(self, parent):
        return len(self.arraydata)

    
    def columnCount(self, parent):
        return len(self.arraydata[0])

    
    def data(self, index, role):
        if not index.isValid():
            return QtCore.Qt.QVariant()
        elif role == QtCore.Qt.DisplayRole:
            return QtCore.QVariant(self.arraydata[index.row()][index.column()])
        else:
            return QtCore.QVariant()


    def headerData(self, col, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return QtCore.QVariant(self.headerdata[col])
        return QtCore.QVariant()

    
    def sort(self, Ncol, order):
        self.layoutAboutToBeChanged.emit()
        self.arraydata = sorted(self.arraydata, key=operator.itemgetter(Ncol))
        if order == QtCore.Qt.DescendingOrder:
            self.arraydata.reverse()
        self.layoutChanged.emit()

        
if __name__ == "__main__":
    main()