I use the Model/View architecture for creating a tree-based structure. The model consists of nodes which can be of several different types.

The tree can look like this:
Root (type a)
child1 (type a)
child2 (type b)
child3 (type a)

Now what I want is to present type a and type b in different ways, say a is supposed to be a circle and b a rectangle.

What is the "correct" way for doing this?


I was thinking about using item roles to define the types. Say type a nodes respond that they are of "a" type when the TypeRole is fetched via the data()-function. Drawing then depends on this role's role, or data. That is, the data()-function for the TypeRole returns a new role that then defines how to draw the node.

Example:
Qt Code:
  1. // We have this in the model
  2. QModelIndex root = model()->index(0,0,0);
  3. QModelIndex child1 = model()->index(0,0,root);
  4. QModelIndex child2 = model()->index(1,0,root);
  5. QModelIndex child3 = model()->index(2,0,root);
  6.  
  7. // Getting the Type is via
  8. int TypeRole = 34; //Available ItemDataRole
  9.  
  10. // Types are
  11. int rootType = root.data(TypeRole);
  12. int child1Type = child1.data(TypeRole);
  13. int child2Type = child2.data(TypeRole);
  14. int child3Type = child3.data(TypeRole);
  15. // rootType == child1Type = child3Type == TYPE_A
  16. // rootType != child2Type == TYPE_B
  17.  
  18.  
  19. // How I thought of doing this is:
  20.  
  21. // Go through nodes and draw them
  22. int childCount = model()->rowCount(index);
  23. for ( int childNum=0; childNum < childCount; childNum++)
  24. {
  25. // Get the child and draw it
  26. QModelIndex child = model()->index( childNum, 0, root );
  27. // Get the type
  28. int type = child.data( TypeRole );
  29. //Draw them depending on the type
  30. switch (type)
  31. {
  32. case (TYPE_A):
  33. drawTypeA(child); //Draws the rectangle
  34. break;
  35. case (TYPE_B):
  36. drawTypeB(child); //Draws the circle
  37. break;
  38. }
  39. }
To copy to clipboard, switch view to plain text mode 

Is this how this is "supposed" to be done, or should the roles instead be directly used, so that drawing draws something only if the node is of correct type?
Qt Code:
  1. //We have several ItemDataRoles defined
  2. int TypeARole = 34;
  3. int TypeBRole = 35;
  4.  
  5. drawNode( child.data( TypeARole ) ); //Draws a rectangle, but only for A-type nodes
  6. drawNode( child.data( TypeBRole ) ); //Draws a circle but only for B-type nodes
To copy to clipboard, switch view to plain text mode 

Or are there other better alternatives?