PDA

View Full Version : Determining QTreeWidget parent



cnbp173
29th March 2011, 19:34
Hello all,

I'm looking for a little help.

I have a QTreeWidget with a number of parents and numerous children, i.e.

parent1
-child
-child
- child
- child
parent2
-child
- child
parent3
-child

I'm using the contextMenuEvent to trigger a slot dependent upon the child picked. As such, I'm trying to determine which parent the child is associated with.

How can I cast the parent of the child even if it is a child of a child?

Cheers
Robbie

ChiliPalmer
29th March 2011, 23:16
QTreeWidgetItem::parent() always works to get the parent of an Item. You have to be careful, though. On the top level this method returns null, not the root Item.

cnbp173
30th March 2011, 02:47
Have done a work around.

item is the QTreeWidgetItem selected



QTreeWidgetItem *upperParent = item;
while(upperParent->parent())
upperParent = upperParent->parent();

if(upperParent==TreeWidget->topLevelItem(0))
......
else if (upperParent==TreeWidget->topLevelItem(1))


This lets me get back up to the parent of any item selected and attach different outcomes dependent on the child choice

Cheers

wysota
30th March 2011, 12:48
Nice spaghetti code, however you can do this:

QTreeWidgetItem *item = ...;
while(item->parent()) item = item->parent();
int index = TreeWidget->invisibleRootItem()->indexOf(item);
switch(index) {
case 0: ...; break;
case 1: ...; break;
// etc.
}

cnbp173
30th March 2011, 18:38
Thanks - that seems a lot more elegant

R

marcp01
23rd April 2013, 14:17
Here's some code I use to expand the tree all the way to the root.

It's a recursive function that accepts a QTreeWidgetItem *item pointer and travels up the tree, starting as position of *item, and expands all parents in the *item's branch until it reaches the *item's topLevelItem.



void MyWidget::expandTree(QTreeWidgetItem *item) {
QTreeWidgetItem *parent = item->parent();
if (parent) {
parent->setExpanded(true);
int topLevel = table->indexOfTopLevelItem(parent);
if (topLevel!=-1) {
QTreeWidgetItem *root = table->topLevelItem(topLevel);
root->setExpanded(true);
} else {
if (item->parent()) {
expandTree(item->parent());
}
}
}
}