May 9, 2012

needhelp_gh needhelp_gh
Ant Farmer
54 posts

[Solved] Qt - How to get parent of QTreeWidgetItem

 

Hi,

Does anyone know how to get parent of a QTreeWidgetItem child?

Thanks!!

 Signature 

————————————————-
http://abstrusegoose.com/432

7 replies

May 9, 2012

Lukas Geyer Lukas Geyer
Gene Splicer
2074 posts

What’s wrong with the existing QTreeWidgetItem::parent() method?

May 9, 2012

needhelp_gh needhelp_gh
Ant Farmer
54 posts

Yes…I suppose I worded my question incorrectly, but thank you.

I meant how can I return the string of the parent in C++ as that method returns a QTreeWidgetItem.

 Signature 

————————————————-
http://abstrusegoose.com/432

May 9, 2012

DerManu DerManu
Robot Herder
451 posts

treeWidgetItem->parent()->text() ?

May 9, 2012

needhelp_gh needhelp_gh
Ant Farmer
54 posts

:) Thanks, DerManu again!

I tried:

treeWidgetItem->parent()->text(column)

Works!!

 Signature 

————————————————-
http://abstrusegoose.com/432

May 10, 2012

Andre Andre
Area 51 Engineer
6031 posts

When dereferencing a pointer, it is wise to check that the pointer is valid first. In your case, the result of parent() may be 0, and then the ->text(column) call would cause a crash.

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

May 10, 2012

needhelp_gh needhelp_gh
Ant Farmer
54 posts

Thank you, Andre. I also noticed that it would crash if the item was the uppermost item & had no parent.

I added this check to my c++ code (might be useful for anyone who comes across this in the future):

  1.     QString cur = item->text(column);
  2.     int root = ui->treeWidget->indexOfTopLevelItem(item);
  3.  
  4.     if ( root.parent() != None ) { // not top most
  5.         QString parent = item->parent()->text(column);
  6.     }
 Signature 

————————————————-
http://abstrusegoose.com/432

May 10, 2012

DerManu DerManu
Robot Herder
451 posts

Are you sure this case isn’t covered by what Andre said? I would expect parent() to simply return 0 on top level items (but I haven’t checked that).

 
  ‹‹ Implement Qt in Windows service      Modal QWidget with a non-QWidget parent ››

You must log in to post a reply. Not a member yet? Register here!