C++ 为什么不能从QVector向QGraphicscene添加项<;QGraphicsItem>;?
我想在链接到C++ 为什么不能从QVector向QGraphicscene添加项<;QGraphicsItem>;?,c++,qt,C++,Qt,我想在链接到QGraphicsView的qgraphicscene中撤消或重做操作:为此,我使用qgraphicselipse(在移动和单击QGraphicsView时绘制点)在mouseMoveEvent方法中,我在QVector中按每个qgraphicselipse,当触发QAction“undo”时,由于myqgraphicscene,程序必须删除myQGraphicsView中绘制的最后一个椭圆(确定的椭圆数) 当我清除我的qgraphicscene并尝试添加在我的QVector中推送的
QGraphicsView
的qgraphicscene
中撤消或重做操作:为此,我使用qgraphicselipse
(在移动和单击QGraphicsView
时绘制点)在mouseMoveEvent
方法中,我在QVector
中按每个qgraphicselipse
,当触发QAction
“undo”时,由于myqgraphicscene
,程序必须删除myQGraphicsView
中绘制的最后一个椭圆(确定的椭圆数)
当我清除我的qgraphicscene
并尝试添加在我的QVector
中推送的所有qgraphicssitems
时,我得到一个错误:我的应用程序关闭了
if(index < historyIndex.size()){
for (int i = 0; i < scHistory.size() - historyIndex[index]; i++){
scene->addItem((QGraphicsItem*)scHistory[i]);
}
index++;
}
if(索引添加项((QGraphicsItem*)故事[i];
}
索引++;
}
QVector的故事;
qgraphicscene::addItem
获取所添加元素的所有权,请检查。这意味着它现在负责破坏元素,这发生在您使用qgraphicscene::clear
清除场景时。从那时起,你的向量就充满了悬空的指针
一个快速修复方法是将对qgraphicscene::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();
if(\u indexHistoryRoam<\u indexHistory.size()){
//仅删除历史记录之外的项目
常量int范围=_sceneHistory.size()-_indexHistory[_indexHistoryRoam];
for(int i=range;i<_sceneHistory.size();i++){
场景->移除项目((QGraphicsItem*)场景历史[i];
删除_sceneHistory[i];//必须销毁项目以避免泄漏
}
_indexHistoryRoam++;
}else{//强制移除所有元素
场景->清除();
}
场景->更新();
什么是\u场景历史
?我认为您需要显示更多的上下文。@drescherjm\u sceneHistory是一个QVector,它包含添加到我的场景中的所有QGraphicsItem。可能QGraphicsItem
会被释放两次<当调用addItem
时,code>qgraphicsecene获取项目的所有权qgraphicscene::clear
删除和删除项目。因此,如果只创建一次QGraphicsItem的QVector,并且多次调用问题中的代码(添加和清除场景),则会多次删除导致崩溃的项。这只是我的假设,因为你没有提供足够的信息来重现你的问题。
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();