我以为我可以使用下面的代码在任何项目离开场景后将其删除,但事实并非如此。在尝试了不同的实现之后,我想我应该尝试另一种方法。一些 QGraphicsItems 实际上是在boundingRect之外开始的,所以我想知道是否有办法在 GraphicsItems 通过某个坐标点后删除和删除它们。
void Scene::advance()
{
QList <QGraphicsItem *> itemsToRemove;
foreach( QGraphicsItem * item, this->items())
{
if( !this->sceneRect().intersects(item->boundingRect()))
{
// The item is no longer in the scene rect, get ready to delete it
itemsToRemove.append(item);
}
}
foreach( QGraphicsItem * item, itemsToRemove )
{
this->removeItem(item);
delete(item);
}
QGraphicsScene::advance();
}
最佳答案
问题出在这一行:-
if( !this->sceneRect().intersects(item->boundingRect()))
这是将场景的矩形(位于场景坐标中)与项目的边界矩形(位于项目的本地坐标系中)进行比较。
您需要转换其中之一,以便在同一坐标系内进行比较。
QRectF itemSceneBoundingRect = item->mapRectToScene(item->boundingRect());
if( !this->sceneRect().intersects(itemSceneBoundingRect)
{
// remove the item.
}
关于c++ - 离开boundingRect后如何删除QGraphicsitems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22977629/