PyQt 4.3 QTableView / QAbstractTableModel sorting example

This is my OLD blog. I've copied this post over to my NEW blog at:

You should be redirected in 2 seconds.

It took me a while to figure out why QTableView's setSortingEnabled method wasn't working. It turns out the sort method in QAbstractItemModel is not implemented. So I had to implement it myself. Hence, my previous post, How to sort a table by columns in Python. I'm not sure if this is the best way to implement the sort method, but I couldn't find anything else out there, and this seems to work for me.

import re
import operator
import os
import sys 
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 
def main(): 
    app = QApplication(sys.argv) 
    w = MyWindow() 
class MyWindow(QWidget): 
    def __init__(self, *args): 
        QWidget.__init__(self, *args) 

        # create table
        table = self.createTable() 
        # layout
        layout = QVBoxLayout()

    def get_table_data(self):
        stdouterr = os.popen4("dir c:\\")[1].read()
        lines = stdouterr.splitlines()
        lines = lines[5:]
        lines = lines[:-2]
        self.tabledata = [re.split(r"\s+", line, 4)
                     for line in lines]

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

        # set the table model
        header = ['date', 'time', '', 'size', 'filename']
        tm = MyTableModel(self.tabledata, header, self) 

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

        # hide grid

        # set the font
        font = QFont("Courier New", 8)

        # hide vertical header
        vh = tv.verticalHeader()

        # set horizontal header properties
        hh = tv.horizontalHeader()

        # set column width to fit contents

        # set row height
        nrows = len(self.tabledata)
        for row in xrange(nrows):
            tv.setRowHeight(row, 18)

        # enable sorting

        return tv
class MyTableModel(QAbstractTableModel): 
    def __init__(self, datain, headerdata, parent=None, *args): 
        """ datain: a list of lists
            headerdata: a list of strings
        QAbstractTableModel.__init__(self, parent, *args) 
        self.arraydata = datain
        self.headerdata = headerdata
    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 QVariant() 
        elif role != Qt.DisplayRole: 
            return QVariant() 
        return QVariant(self.arraydata[index.row()][index.column()]) 

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

    def sort(self, Ncol, order):
        """Sort table by given column number.
        self.arraydata = sorted(self.arraydata, key=operator.itemgetter(Ncol))        
        if order == Qt.DescendingOrder:

if __name__ == "__main__": 

No comments:


This is my *OLD* blog. I've copied all of my posts and comments over to my NEW blog at:

Please go there for my updated posts. I will leave this blog up for a short time, but eventually plan to delete it. Thanks for reading.