How to remove a QGraphicsRectItem from a QVector?

321 Views Asked by At

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]);

 }
1

There are 1 best solutions below

0
On

You are mixing iterators and actual values of your vector:

vec.begin() + i returns an iterator, while vec[i] returns the actual value (QGraphicsItem*). For delete and removeItem() you simply need vec[i], while e.g. erase() would take the iterator.

When you delete a QGraphicsItem, it is automatically removed from the scene, so you do not need to call removeItem() explicitly.

So for deleting all items in vec (and clearing vec), you can do:

for (int i = 0; i < vec.size(); ++i)
    delete vec[i];
vec.clear();

Or, shorter:

qDeleteAll(vec);
vec.clear();

To delete a single item without looping:

delete vec.take(index);