Reputation: 47
I am using the QGraphicsScene in Qt5 to add different QGraphicsItems. Some of them have further child items, some not. But now I need the possibility to find all top-level items. Surely, I could write a method, which would use the QList<QGraphicsItem *> QGraphicsScene::items(...) const
method and then iterating through the returned list, looking for all items, that would return 0
as their parent. But probably the returned list will be long with only very few top-level items.
So, is there any better solution?
Upvotes: 2
Views: 1899
Reputation: 14623
I'd try with:
QGraphicsItem * QGraphicsItem::topLevelItem () const
because in most practical situations, there is only one top-level item. Otherwise you need to go with one of the items()
methods. If you choose the descending sort order, you can stop iterating as soon as you find that an item has a parent.
Upvotes: 0
Reputation: 2001
DIT :
The method QGraphicsScene::items()
returns the items sorted by depth IIRC, so you can cycle through it until the parent isn't null. This should be linear with regards to the number of top level items which is probably the best you can do.
it appears I was mistaken, this method returns the items sorted depth-first which is the opposite of what we want.
However there are also overloads that allow you to sort them by name.
I suggest you use nomenclature to identify all top-level item (say all their names start with "__top")
You can then loop while (name.startsWith("__top"))
Upvotes: -1