artomason
artomason

Reputation: 3993

How to populate QTreeWidget from tuple?

I'm pretty new to Python so please bear with me. I'm trying to populate a QTreeWidget from a tuple, but I can't seem to get it too work.

TreeList = ({

    'Header1': ((
        'Item1',
        'Item2',
    )),

    'Header2': ((
        'Item1',
        'Item2'
    ))
})

The idea is that I want to create a QTreeWidget that looks like:

ROOT
  |
  |-- Header1
  |    |-- Item1
  |    |-- Item2
  |
  |-- Header2
       |-- Item1
       |-- Item2

I have been searching around online to find a solution, but nothing I try seems to work, what would be the best way to go about this.

widget = QTreeWidget()

for i in TreeList:
    val = QTreeWidgetItem([i])
    widget.addTopLevelItem(val)

for i in TreeList['Header1']
    val = QTreeWidgetItem([i])
    widget.Header1.addChild(val)  # DONT THINK THIS IS RIGHT

for i in TreeList['Header2']
    val = QTreeWidgetItem([i])
    widget.Header2.addChild(val)  # DONT THINK THIS IS RIGHT

The first for-loop works, and the headers get listed under the root element, but the second two for-loops don't work at all. What am I doing wrong? I have sifted through the documentation and everything suggests that I should used addChild() but PyCharm says:

'QTreeWidget' object has no attribute 'addChild'

I'm using Python 3.6 with PyQt5. Thanks!

Upvotes: 2

Views: 1250

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

A QTreeWidgetItem can be passed directly to the parent, but it needs a list or tuple of items as shown below:

import sys

from PyQt5.QtWidgets import *

TreeList = ({

    'Header1': ((
        'Item11',
        'Item12',
    )),

    'Header2': ((
        'Item21',
        'Item22'
    ))
})

app = QApplication(sys.argv)

tree = QTreeWidget()

for key, value in TreeList.items():
    root = QTreeWidgetItem(tree, [key])
    for val in value:
        item = QTreeWidgetItem([val])
        root.addChild(item)
        # Or
        # QTreeWidgetItem(root, [val])

tree.expandAll()
tree.show()
sys.exit(app.exec_())

Output:

enter image description here

Upvotes: 5

Related Questions