我有一个填充了QGraphicsRectItem元素(小矩形)的QVector,当用户单击它时,我需要删除一个矩形。我试着使用removeItem(vec.begin() + i)和delete vec.begin() + i函数,removeItem(vec[i])和delete vec[i],vec.erase(vec.begin() + 1)。但在第一种情况下,程序员输出一条消息:
C:\Users\1\Documents\my_game\myscene.cpp:24: error: no matching function for call to 'myscene::removeItem(QVector<QGraphicsRectItem*>::iterator)' removeItem(vec.begin() + i);在第二种情况下,当我单击一个矩形时,它会移除所有矩形。
在第三种情况下,它根本不起作用。
你能给我一些其他的方法来解决我的问题吗?
代码如下:
#include "myscene.h"
#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QTimer>
#include <QVector>
#include <ctime>
#include <QGraphicsSceneMouseEvent>
myscene::myscene(QObject *parent)
{
srand(time(NULL));
QTimer *t = new QTimer;
t->setInterval(1000);
connect(t, SIGNAL(timeout()), this, SLOT(addrect1()));
t->start();
}
void myscene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
int x1 = event->scenePos().x();
int y1 = event->scenePos().y();
for(int i=0; i<vec.size(); i++){
if ((x1=vec_x[i])&&(y1=vec_y[i])) {
removeItem(vec.begin() + i);
delete vec.begin() + i;
}
}
}
myscene::addrect1()
{
QGraphicsRectItem *newRECT = new QGraphicsRectItem;
x=rand()%481-240;
y=rand()%481-240;
newRECT->setRect(x,y,10,10);
vec.push_back(newRECT);
vec_x.push_back(x);
vec_y.push_back(y);
this->addItem(vec[vec.size()-1]);
}发布于 2020-04-24 15:19:55
您混合了迭代器和向量的实际值:
vec.begin() + i返回迭代器,而vec[i]返回实际值(QGraphicsItem*)。对于delete和removeItem(),您只需要vec[i],而例如erase()将使用迭代器。
当您删除QGraphicsItem时,它是automatically removed from the scene,因此您不需要显式调用removeItem()。
因此,要删除vec中的所有项(并清除vec),您可以执行以下操作:
for (int i = 0; i < vec.size(); ++i)
delete vec[i];
vec.clear();或者,简称:
qDeleteAll(vec);
vec.clear();要删除单个项目而不循环,请执行以下操作:
delete vec.take(index);https://stackoverflow.com/questions/61400701
复制相似问题