【问题标题】:Lots of pointer casts in QGraphicsView framework and performanceQGraphicsView 框架和性能中的大量指针转换
【发布时间】:2011-03-02 00:41:10
【问题描述】:

由于 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 评估吗?

【问题讨论】:

  • +1 因为我有同样的问题。值得注意的一点是,您可以使用 setData()/data() 方法针对每个 QGraphicsItem 存储任意数据(QVariant),通过键访问数据。这可能很有用。

标签: c++ qt4 qgraphicsview qgraphicsitem


【解决方案1】:

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

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

【讨论】:

  • 啊,你的意思是在 foreach 块的开头获取一次?这是一个很好的观点。
  • 是的。现在您正在为每次比较获取它。我认为这是一个虚拟通话,虽然便宜,但它们不是免费的。将其乘以每个场景中的每个对象,您就会得到很多便宜的调用——那么就不再那么便宜了。
猜你喜欢
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2019-10-06
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多