Friday, January 27, 2012

Qt 4.8 Model/View Tutorial - Part 1

The following code was adapted from the Qt Model/View Tutorial - 2.1 A Read Only Table.



#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'''
    PyQt4 conversion of Qt Model-View Tutorial
    
     Creating a read-only Table View using QTableView
     
    NOTES:
    =====
    For some reason, calling a main() function to start the
    application as in earlier examples produces a runtime error 
    when the application is closed:
        QObject::startTimer: QTimer can only be used with threads 
          started with QThread

    Start the application directly and no error occurs.
    
last modified: 2012-01-27 jg
ref:
    http://developer.qt.nokia.com/doc/qt-4.8/modelview.html
    
'''
from PyQt4.QtGui import (QApplication, QTableView)
from PyQt4.QtCore import (Qt, QAbstractTableModel, QModelIndex, QVariant)

class MyModel(QAbstractTableModel):
    def __init__(self, parent=None):    # initialise base class
        super(MyModel, self).__init__(parent)

    def rowCount(self, index=QModelIndex()):
        return 2

    def columnCount(self, index=QModelIndex()):
        return 3

    def data(self, index, role):
        if role == Qt.DisplayRole:
            return "Row {0}, Column {1}".format(index.row() + 1,
                                                index.column() + 1)
        else:
            return None

# main ========================================================================

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    tv = QTableView()

    myModel = MyModel()
    tv.setModel(myModel)
    tv.setWindowTitle("Read-only Table View")
    tv.show()


    sys.exit(app.exec_())