QTreeWidget to Mirror python Dictionary

chase picture chase · Feb 16, 2014 · Viewed 9.2k times · Source

Is there a way to make a QTreeWidget mirror the changes made to an internal data structure such as dictionary? It seems like they would have created this functionality within the api, because there are many programs which may interact with QTreeWidgets from multiple GUI areas, but the main purpose required of the QTreeWidget is to show a data structure at any point in time. The documentation for QtGui items is not that simple for me to grasp as it usually refers to C documentation, and I'm not certain how it transfers to python.

So essentially what I would like is the simplest manner to make a QTreeWidget show a nested dictionary, where the top level corresponds to the keys and the sub level corresponds to the values. Also, if the values are dictionaries, use the keys in that level and make sub levels for the values, etc.

Is this easily doable? I have not been able to find anything to do simple mirroring of data structres like this yet.

Answer

Pavel Strakhov picture Pavel Strakhov · Feb 16, 2014

This is a straightforward implementation:

def fill_item(item, value):
  item.setExpanded(True)
  if type(value) is dict:
    for key, val in sorted(value.iteritems()):
      child = QTreeWidgetItem()
      child.setText(0, unicode(key))
      item.addChild(child)
      fill_item(child, val)
  elif type(value) is list:
    for val in value:
      child = QTreeWidgetItem()
      item.addChild(child)
      if type(val) is dict:      
        child.setText(0, '[dict]')
        fill_item(child, val)
      elif type(val) is list:
        child.setText(0, '[list]')
        fill_item(child, val)
      else:
        child.setText(0, unicode(val))              
      child.setExpanded(True)
  else:
    child = QTreeWidgetItem()
    child.setText(0, unicode(value))
    item.addChild(child)

def fill_widget(widget, value):
  widget.clear()
  fill_item(widget.invisibleRootItem(), value)

I added list support just in case anyone needs it.

Usage:

d = { 'key1': 'value1', 
  'key2': 'value2',
  'key3': [1,2,3, { 1: 3, 7 : 9}],
  'key4': object(),
  'key5': { 'another key1' : 'another value1',
            'another key2' : 'another value2'} }

widget = QTreeWidget()
fill_widget(widget, d)
widget.show()

Result:

screenshot