4

I presently have a QTreeWidget named 'treeWidget', and for the life of me, cannot figure out how to get the index value or the text of the selected treeWidget branch.

self.treeWidget looks like:
User
-Inbox
-Sent
-Drafts
-Trash

I need to know which branch is selected so I can display folders in the branch's corresponding file folder. I've been trying to understand the Qt documentation, but I'm totally stumped by the C++. And the PyQt docs don't have any examples. I've searched everywhere for three days trying to tinker and figure out the answer but keep coming up with errors.

The closest I think I've come is something like this:

self.connect(self.treeWidget,SIGNAL("itemSelectionChanged()"), self.loadAllMessages)

def loadAllMessages(self, folder):
    item = self.treeWidget.currentItem()

Do I need to setSelectionMode first or something? All help is greatly appreciated!

Ang
  • 43
  • 1
  • 1
  • 3

2 Answers2

8

Try This

#remove the old way of connecting
#self.connect(self.treeWidget,SIGNAL("itemSelectionChanged()"), self.loadAllMessages)
self.treeWidget.itemSelectionChanged.connect(self.loadAllMessages)
def loadAllMessages(self, folder):
    getSelected = self.treeWidget.selectedItems()
    if getSelected:
        baseNode = getSelected[0]
        getChildNode = baseNode.text(0)
        print getChildNode
Achayan
  • 5,720
  • 2
  • 39
  • 61
  • Can I also get the index number of the selected child this way? It seems like I can't just substitute '.indexOfChild' for '.text'. The PyQt docs say "int indexOfChild (self, QTreeWidgetItem achild)", but I don't know what I should put as the QTreeWidgetItem achild part... – Ang Sep 19 '14 at 13:04
  • You need to use indexFromItem to find it. Something like itmIndex =self.treeWidget.indexFromItem(baseNode) – Achayan Sep 19 '14 at 17:46
  • Hmmm...tried
    print self.treeWidget.indexFromItem(baseNode)
    but it kept spitting out "". Tried changing different things but couldn't get it to work... Any ideas?
    – Ang Sep 22 '14 at 03:21
0

Following Achayans answer and comments, you get the index as a QModelIndex by using .indexFromItem(). To retrive now the real index, you need to use .row() which is described here and shown in the following code:

self.treeWidget.itemSelectionChanged.connect(self.loadAllMessages)
def loadAllMessages(self, folder):
getSelected = self.treeWidget.selectedItems()
if getSelected:
    baseNode = getSelected[0]
    qmIndex = self.treeWidget.indexFromItem(baseNode)
    itemIndex = qmIndex.row()
    print('Selected index: ', itemIndex)
Dennis
  • 171
  • 3
  • 16