#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
PyQt4 conversion of Qt Model-View Tutorial
We use QStandardItemModel, which is a container for hierarchical
data that also implements QAbstractItemModel.
To show a tree, QStandardItemModel must be populated with
QStandardItems, which are able to hold all the standard properties
of items like text, fonts, checkboxes or brushes.
NOTES:
=====
The original C++ code did not include:
stdModel.setColumnCount(COLUMNS)
so only one column was being displayed
QList is not implemented in PyQt4, a standard Python
list is used instead.
last modified: 2012-01-28 jg
ref:
http://developer.qt.nokia.com/doc/qt-4.8/modelview.html#3-1-treeview
'''
from PyQt4.QtGui import (QApplication, QMainWindow, QTreeView, QStandardItem,
QStandardItemModel)
ROWS = 2
COLUMNS = 3
class MainWindow(QMainWindow):
def __init__(self, parent=None): # initialise base class
super(MainWindow, self).__init__(parent)
treeView = QTreeView(self)
self.setCentralWidget(treeView)
stdModel = QStandardItemModel()
stdModel.setColumnCount(COLUMNS) # columns to display
# create the first row of items and assign it to the
# tree root
preparedRow = self.prepareRow("first", "second", "third")
item = stdModel.invisibleRootItem()
item.appendRow(preparedRow)
# add a second row of items to the first item in the first row
secondRow = self.prepareRow("111", '222', '333')
preparedRow.appendRow(secondRow)
treeView.setModel(stdModel)
treeView.expandAll()
def prepareRow(self, first, second, third):
# create a list of QStandardItems
items = []
items.append(QStandardItem(first))
items.append(QStandardItem(second))
items.append(QStandardItem(third))
# create a QStandardItem and add the list
# as a row
rowItems = QStandardItem()
rowItems.appendRow(items)
return rowItems
# main ========================================================================
def main():
import sys
app = QApplication(sys.argv)
mw = MainWindow()
mw.setWindowTitle("Tree View")
mw.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Page List
▼
Friday, January 27, 2012
Qt 4.8 Model/View Tutorial - Part 6
The following code is based on Qt 4.8 Model/View Tutorial - 3.1 Tree View.