I have a QVector filled with QGraphicsRectItem elements (little rectangles) and I need to remove one single rectangle when a user clicks on it. I tried to use removeItem(vec.begin() + i)
and delete vec.begin() + i
functions, removeItem(vec[i])
and delete vec[i]
, vec.erase(vec.begin() + 1)
. But in the first case a programm outputs a message:
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);
In the second case when I click on a rectangle it removes all the rectangles.
And in the third case it simply doesn't work.
Could you advise me some other method to solve my problem?
Here's the code:
#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]);
}