SaltyCrane Blog — Notes on JavaScript and web development

PyQt 4.3 QTableView / QAbstractTableModel formatting example

This example displays the output of the "dir" command using QTableView and QAbstractTableModel. It adds some more formatting to my previous example such as specifying the font, a header, column width, row height, etc.

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

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

    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) 
        tv.setModel(tm)

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

        # hide grid
        tv.setShowGrid(False)

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

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

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

        # set column width to fit contents
        tv.resizeColumnsToContents()

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

        # enable sorting
        # this doesn't work
        #tv.setSortingEnabled(True)

        return tv
 
class MyTableModel(QAbstractTableModel): 
    def __init__(self, datain, headerdata, parent=None, *args): 
        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()

if __name__ == "__main__": 
    main()

Comments


#1 aatiis commented on :

Thanks a lot Sofeng, it is very helpful.

Could you please show me how to put other widgets inside a treeview? e.g. checkboxes, combo boxes, etc.


#2 Bernd F. commented on :

Great example. I had to do the following changes to run it on linux (where there is no C partition and thus no example data is found):

def get_table_data(self):
    stdouterr = os.popen4("ls -l /usr/bin")[1].read()
    lines = stdouterr.splitlines()
    lines = lines[5:]
    lines = lines[:-2]
    self.tabledata = [re.split(r"\s+", line, 8)
                 for line in lines]

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

    # set the table model
    header = ['permissions', '', 'owner', 'grp', 'size',"mnt","d","year","filename"]

#3 Eliot commented on :

Bernd F., Thanks for the Linux example!


#4 atm commented on :

Thanx Bernd F. for the Linux example...


#5 komal commented on :

hii

disqus:3114158018


#6 Ivan commented on :

Is it possible somehow to set fixed width and height of any column inserted?

disqus:3708606598