![](/img/trans.png)
[英]Deleting a QGraphicsItem/QGraphicsObject from QGraphicsScene?
[英]Why cannot addItem into QGraphicsScene from a QVector<QGraphicsItem>?
我想在撤消或重做动作QGraphicsScene
链接到一个QGraphicsView
:对于这一点,我用QGraphicsEllipse
(画点,而移动和点击QGraphicsView
)在我mouseMoveEvent
方法,我把每QGraphicsEllipse
在QVector<QGraphicsItem>
,并且当QAction
“撤消”被触发时,由于我的QGraphicsScene
,程序必须删除在我的QGraphicsView
绘制的最后一个椭圆(确定的椭圆数量)。
当我清除我的QGraphicsScene
并尝试添加在我的QVector<QGraphicsItem>
中推送的所有QGraphicsItems
,我收到一个错误:我的应用程序宕机了!
if(index < historyIndex.size()){
for (int i = 0; i < scHistory.size() - historyIndex[index]; i++){
scene->addItem((QGraphicsItem*)scHistory[i]);
}
index++;
}
QVector<QGraphicsItem *> scHistory;
QGraphicsScene::addItem
获取添加元素的所有权,请检查doc 。 这意味着它现在负责销毁元素,当您使用QGraphicsScene::clear
场景时会发生这种情况。 从那时起,您的向量就充满了悬空指针。
一种快速解决方法是通过QGraphicsScene::removeItem
手动删除项目来替换对QGraphicsScene::clear
的调用,这不会破坏项目(它将所有权返回给调用者)。 然后,只销毁那些实际不在场景中的元素,并将其余元素添加回来。 另一种更有效的选择是仅删除您需要的元素,保留其余元素,这样您还可以通过避免从历史记录中添加大量项目来提高性能。
如果不完全了解您的代码,则第二个选项可能类似于:
if(_indexHistoryRoam < _indexHistory.size()){
// Remove only items beyond history
const int range = _sceneHistory.size() - _indexHistory[_indexHistoryRoam];
for (int i = range; i < _sceneHistory.size(); i++){
scene->removeItem((QGraphicsItem*)_sceneHistory[i]);
delete _sceneHistory[i]; // item must be destroyed to avoid a leak
}
_indexHistoryRoam++;
} else { // force removal of all elements
scene->clear();
}
scene->update();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.