简体   繁体   English

是否有可能在Qt QGraphicsScene中获得顶级项目?

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

I am using the QGraphicsScene in Qt5 to add different QGraphicsItems. 我在Qt5中使用QGraphicsScene来添加不同的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. 当然,我可以编写一个方法,该方法将使用QList<QGraphicsItem *> QGraphicsScene::items(...) const方法,然后遍历返回的列表,查找所有将返回0作为其父项的项。 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. 否则,您需要使用items()方法之一。 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. DIT:方法QGraphicsScene::items() 返回按深度IIRC排序的项目,因此您可以循环浏览直到父级不为空。 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")) 我建议您使用命名法来标识所有顶级项(例如,其所有名称均以“ __top”开头),然后可以while (name.startsWith("__top"))循环while (name.startsWith("__top"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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