View Full Version : Display properties of single item in QTableView based on selection in QTreeView

23rd July 2015, 20:14

This is my first time using PyQt. I am attempting to parse an XML file and display the hierarchy in a QTreeview and allow the user to edit the properties of a particular element in a QTableView. I have successfully parsed the XML using etree and populated a QStandardItemModel. I've been trying to figure out the QItemViewDelegate but have not had much success yet.

My issue is this: When I select an item in the QTreeView how can I update the QTableView to only display the properties of the selected element?

My other issue is I still need to figure out how to populate the attributes in the QStandardItemModel (I assume I need to add to qt.UserRole with setData, but I have not gotten that far in yet).

As an example: I want to select Tab1 in the QTreeView and in the QTableView I want to see only

Field | Value
Name | tab1
img | xyz.jpg
uid | 123

Below is my python code

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.uic import *
import xml.etree.ElementTree as ET

class Window(QMainWindow):

def __init__(self):

# -- Load QT .ui file --
self.ui = loadUi('test.ui')
# ----

# -- Display UI using QT ui layout --
# ----

# -- Initialize data models for Treeview and Tableview
self.modelTreeView = QStandardItemModel()
self.modelTableView = QStandardItemModel()
self.ui.ItemProperties.setModel(self.modelTreeView )
# ----

#UI Tree view item selection
self.connect(self.ui.XMLTreeView.selectionModel(), SIGNAL("selectionChanged(QItemSelection, QItemSelection)"), fnXMLUpdate)
tree = ET.parse('test.xml')
root = tree.getroot()
temp = tree.findall(".//tab[@uid='123']")
parseXML(self.modelTreeView, root)
# ----

#UI Decorations
# ----

def fnXMLUpdate(current,previous):
print("new item selected in tree view")
index = window.ui.XMLTreeView.selectedIndexes()[0]
crawler = index.model().itemFromIndex(index)
print "Node Name: %s" % crawler.data(Qt.DisplayRole).toString()
print "Node uid: %s" % uid

print("end new tree view")

item = QStandardItem()
item.setData(crawler.data(Qt.UserRole), Qt.DisplayRole)
item.setData(crawler.data(Qt.UserRole), Qt.UserRole)


def parseXML(parent, node):
for element in node:
item = QStandardItem()
item.setData(element.attrib.get('name'), Qt.DisplayRole)
item.setData(element.attrib.get('uid'), Qt.UserRole)
parseXML(item, element)

if __name__ == "__main__":

app = QApplication(sys.argv)
window = Window()

Attached is the XML and UI file