#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' PyQt4 conversion of Qt Model-View Tutorial Extends the Read-Only example with Roles NOTES: ===== The only changes are in the data() method. last modified: 2012-01-27 jg ref: http://developer.qt.nokia.com/doc/qt-4.8/modelview.html#2-2-extending-the-read-only-example-with-roles ''' from PyQt4.QtGui import (QApplication, QTableView, QFont, QBrush) 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): row = index.row() col = index.column() if role == Qt.DisplayRole: if (row == 0 and col == 1): return "<-- left" if (row == 1 and col == 1): return "right -->" return "Row {0}, Column {1}".format(row + 1, col + 1) elif role == Qt.FontRole: if (row == 0 and col == 0): bold = QFont() bold.setBold(True) return bold elif role == Qt.BackgroundRole: if (row == 1 and col == 2): return QBrush(Qt.red) elif role == Qt.TextAlignmentRole: if(row == 1 and col == 1): return Qt.AlignRight + Qt.AlignVCenter elif role == Qt.CheckStateRole: if (row == 1 and col == 0): return Qt.Checked else: return None # main ======================================================================== if __name__ == '__main__': import sys app = QApplication(sys.argv) tv = QTableView() myModel = MyModel() tv.setModel(myModel) tv.setWindowTitle("Format Table with Roles") tv.show() sys.exit(app.exec_())
Page List
▼
Friday, January 27, 2012
Qt 4.8 Model/View Tutorial - Part 2
The following code was adapted from the Qt Model/View Tutorial - 2.2 Extending the Read Only Example with Roles.