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.
I've solved this by iterating from the current selected item all the way up to trace the parent of the item using a while loop. Note that I'm using PyQt5/PySide2 for this code.
treewidget = self.ui.treeWidget_size
# Initialise an Empty list to store the indexes
level_list = []
current_item = treewidget.currentItem()
current_index = treewidget.indexFromItem(current_item)
if current_index.isValid():
level_list.append(current_index.row())
# Iterate through all the item's parents
while current_index.isValid():
current_item = treewidget.itemFromIndex(current_index.parent())
# Get the parent of the item and find the index of it's parent until we reach the top
current_index = treewidget.indexFromItem(current_item)
if current_index.isValid():
level_list.append(current_index.row())
#Once done getting indexes, reverse_list
level_list = level_list[::-1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.