Hi everyone,

I'm trying to use QTreeWidgetItem to display a hierarchy of categories for a blog, as is found in Wordpress. I thought I could create a QMap of QListWidgetItem pointers with the category ID as the key, then iterate through the list and add each item to its relevant parent, like so:


Qt Code:
  1. // Now add all the categories into a big list
  2. for( b = 0; b < catsToDisplay; b++ ) {
  3. catItem = new QTreeWidgetItem;
  4. id = mainCatList.at( b ).firstChildElement( "categoryId" ).text();
  5. //qDebug() << "id =" << id;
  6. catItem->setText( 0, decodeXmlEntities( mainCatList.at( b ).firstChildElement( "categoryName" ).text() ) );
  7. description = decodeXmlEntities( mainCatList.at( b ).firstChildElement( "description" ).text() );
  8. if( !description.isEmpty() )
  9. catItem->setStatusTip( 0, description );
  10. catItem->setData( 0, Qt::UserRole, QVariant( id ) );
  11. catItem->setData( 0, 33, QVariant( false ) ); // i.e. not primary category until required
  12. catItems[id] = catItem;
  13. }
  14. qDebug() << "done the top-level categories";
  15. // Now assign each category to its respective parent, and make a list of
  16. // top-level items
  17. Q_FOREACH( QTreeWidgetItem *item, catItems ) {
  18. thisId = item->data( 0, Qt::UserRole ).toString();
  19. qDebug() << "now doing" << thisId;
  20. if( thisId != "0" && catItems.contains( thisId ) ) {
  21. qDebug() << "not a top-level";
  22. thisItem = catItems[thisId];
  23. qDebug() << "got item" << thisItem->data( 0, Qt::UserRole ).toString();
  24. Q_ASSERT( thisItem != 0 );
  25. thisItem->addChild( item );
  26. }
  27.  
  28. if( thisId == "0" ) {
  29. qDebug() << "top-level";
  30. topLevelCatItems.append( item );
  31. }
  32. qDebug() << "have now done" << thisId;
  33. }
To copy to clipboard, switch view to plain text mode 

The full method can be found here at my Bitbucket hg repo.

The program halts at line 25 -- where it tries to add a child QTreeWidgetItem to one that doesn't have a parent. My aim in doing this was to build up a tree of items which could all be added, in one go, to the QTreeWidget, because it seems more efficient than having to run several recursive loops, and also because the user wouldn't have to watch the tree appear bit by bit.

It doesn't crash or segfault; it just stops and you have to kill the process.

Can anyone tell me what I'm doing wrong here? It doesn't say in the documentation that you can't add a child to a parentless item.

Regards,

Matt