I created PyQt4 QTreeWidget and added following QTreeWidgetItem structure.
treeWidget = QTreeWidget()
twi = QTreeWidgetItem(['Level_1'])
twi.addChild( QTreeWidgetItem( ['SubLevel_1_1'] ) )
twi.addChild( QTreeWidgetItem( ['SubLevel_1_2'] ) )
twi.addChild( QTreeWidgetItem( ['SubLevel_1_3'] ) )
twi.addChild( QTreeWidgetItem( ['SubLevel_1_4'] ) )
treeWidget.addTopLevelItem( twi )
I want to get parent (top level item) and child indexes when selected child item.
First of all, if you are planning on accessing a widget from a method, I would make it a property of your parenting widget/GUI, so
self.treeWidget = QTreeWidget()
Then in your example you forgot to add the top level item
self.treeWidget.insertTopLevelItem(0,twi)
To find out your current selection you can then add something like this:
def getCurrentItems(self):
"""Returns Current top level item and child index.
If no child is selected, returns -1.
"""
#Check if top level item is selected or child selected
if self.treeWidget.indexOfTopLevelItem(self.treeWidget.currentItem())==-1:
return self.treeWidget.currentItem().parent(),self.treeWidget.currentItem().parent().indexOfChild(self.treeWidget.currentItem())
else:
return self.treeWidget.currentItem(),-1
And then connect the method via:
self.treeWidget.itemActivated.connect(self.getCurrentItems)
Hope that helps.