#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' PyQt4 conversion of Qt Model-View Tutorial Build a selectable tree view and update the application's Window Title with the selected item's content and hierarchy level. NOTES: ===== Tree is displayed as one expandable column. last modified: 2012-01-28 jg ref: http://developer.qt.nokia.com/doc/qt-4.8/modelview.html#3-2-working-with-selections ''' from PyQt4.QtGui import (QApplication, QMainWindow, QTreeView, QStandardItem, QStandardItemModel, QItemSelection) from PyQt4.QtCore import (pyqtSlot, Qt, QModelIndex) ROWS = 2 COLUMNS = 3 class MainWindow(QMainWindow): def __init__(self, parent=None): # initialise base class super(MainWindow, self).__init__(parent) self.treeView = QTreeView(self) self.setCentralWidget(self.treeView) stdModel = QStandardItemModel() rootNode = stdModel.invisibleRootItem() # define a few items americaItem = QStandardItem("America"); mexicoItem = QStandardItem("Canada"); usaItem = QStandardItem("USA"); bostonItem = QStandardItem("Boston"); europeItem = QStandardItem("Europe"); italyItem = QStandardItem("Italy"); romeItem = QStandardItem("Rome"); veronaItem = QStandardItem("Verona"); # build the hierarchy rootNode.appendRow(americaItem); rootNode.appendRow(europeItem); americaItem.appendRow(mexicoItem); americaItem.appendRow(usaItem); usaItem.appendRow(bostonItem); europeItem.appendRow(italyItem); italyItem.appendRow(romeItem); italyItem.appendRow(veronaItem); # register the model self.treeView.setModel(stdModel) self.treeView.expandAll() # connect selection signal to slot selModel = self.treeView.selectionModel() selModel.selectionChanged.connect(self.selChanged) @pyqtSlot(QItemSelection, QItemSelection) def selChanged(self, newSel, oldSel): # get selected item's text index = self.treeView.selectionModel().currentIndex() selText = index.data(Qt.DisplayRole) # find the selected item's hierarchy level hierLevel = 1 seekRoot = index while seekRoot.parent() != QModelIndex(): seekRoot = seekRoot.parent() hierLevel += 1 # update the window title showString = "{0}, Level {1}".format(selText, hierLevel) self.setWindowTitle(showString) # main ======================================================================== def main(): import sys app = QApplication(sys.argv) mw = MainWindow() mw.setWindowTitle("Tree View Selections") mw.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
Friday, January 27, 2012
Qt 4.8 Model/View Tutorial - Part 7
The following code is based on Qt 4.8 Model/View Tutorial - 3.2 Working with Selections.
Labels:
Qt Model/View Tutorial