简体   繁体   中英

Is there a possibility to get top-level items in a Qt QGraphicsScene?

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?

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.

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM