Determining QTreeWidget parent
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
Re: Determining QTreeWidget parent
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.
Re: Determining QTreeWidget parent
Have done a work around.
item is the QTreeWidgetItem selected
Code:
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
Re: Determining QTreeWidget parent
Nice spaghetti code, however you can do this:
Code:
while(item->parent()) item = item->parent();
int index = TreeWidget->invisibleRootItem()->indexOf(item);
switch(index) {
case 0: ...; break;
case 1: ...; break;
// etc.
}
Re: Determining QTreeWidget parent
Thanks - that seems a lot more elegant
R
Re: Determining QTreeWidget parent
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.
Code:
if (parent) {
parent->setExpanded(true);
int topLevel = table->indexOfTopLevelItem(parent);
if (topLevel!=-1) {
root->setExpanded(true);
} else {
if (item->parent()) {
expandTree(item->parent());
}
}
}
}