Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

PyQt 4.2 QAbstractTableModel/QTableView Example

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

my_array = [['00','01','02'],
            ['10','11','12'],
            ['20','21','22']]

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)

        tablemodel = MyTableModel(my_array, self)
        tableview = QTableView()
        tableview.setModel(tablemodel)

        layout = QVBoxLayout(self)
        layout.addWidget(tableview)
        self.setLayout(layout)

class MyTableModel(QAbstractTableModel):
    def __init__(self, datain, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.arraydata = datain

    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()])

if __name__ == "__main__":
    main()

3 Comments — feed icon Comments feed for this post


#1 Vondor commented on 2010-03-10:

Thats great. Now I finally understand how it works. Thanks!


#2 Glenn commented on 2010-04-08:

But this fragment doesn't work with the latest stuff:

File "D:mypytest7.py", line 42, in data return QVariant() TypeError: PyQt4.QtCore.QVariant represents a mapped type and cannot be instantiated


#3 Nader commented on 2011-08-22:

Add this to the top of the file to make it run using PyQt version 4.7.3

import sip sip.setapi('QVariant', 1)

from PyQt4.QtCore import from PyQt4.QtGui import import sys

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Linode