gpt4 book ai didi

c++ - QGraphicsView 框架和性能中的大量指针转换

转载 作者:太空狗 更新时间:2023-10-29 23:20:13 26 4
gpt4 key购买 nike

由于 QGraphicsScene 和 QGraphicsItem 的大部分便利函数(例如 items()、collidingItems()、childItems() 等)返回一个 QList,你不得不做很多 qgraphicsitem_cast 或 static_cast 和 QGraphicsItem::Type( ) 当场景中有很多不同类型的元素时,检查以获取实际元素。我认为进行大量子类转换并不是一种理想的编码风格,但我想在这种情况下没有其他可行的方法,或者是否存在?

QList<QGraphicsItem *> itemsHit = someItem->collidingItems(Qt::IntersectsItemShape);
foreach (QGraphicsItem *item, itemsHit) {
if (item->type() == QGraphicsEllipseItem::type()) {
QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(item);
// do something
}
else if (item->type() == MyItemSubclass::type()) {
MyItemSubClass *myItem = qgraphicsitem_cast<MyItemSubClass *>(item);
// do something
}
// etc
}

上面的 qgraphicsitem_cast 可以用 static_cast 代替,因为已经验证了正确的类型。当一直做很多这样的事情时(非常动态的场景),除了正常的 if-else 评估之外,大量的转换会影响性能吗?

最佳答案

性能开销大部分是预付的;这是拥有 . type()成员。检索 item->type() 可能是有效的一次。您知道它不会改变,但编译器很可能不会改变。

[编辑]此外,如果您真的有很多类型,那么引入一些中间类型可能是值得的。例如。 if (dynamic_cast<MyGraphicsInterMediateType*>(item)) {/* check those types */} else {/* other types */}

关于c++ - QGraphicsView 框架和性能中的大量指针转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3012169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com