-1

I am creating a simple game using QT c ++, I have an asteroid class and a Qvector of said class. Every 15 seconds an asteroid is created and added to the Qvector.

void MainWindow::generarAsteroides(){
     srand(time(NULL));
     int aleatorio=1+rand()%1000;
     int a_w = 30+rand()%200;
     v_asteroides.push_back(new asteroides(aleatorio,-1000,a_w,a_w,500));
     mundo->addItem(v_asteroides.last());
     std::cout << "Asteroide generado en X : "<< aleatorio << std::endl;
     sonido->stop();
     sonido->setMedia(QUrl("qrc:/multimedia/suspenso1.mp3"));
     sonido->play();

}

when it exceeds a certain Y coordinate, I call a function through a Timer to traverse the vector and eliminate from the scene with

void MainWindow::actualizar(){
for(auto &ast : v_asteroides){
    if(ast->destruir()){

        mundo->removeItem(ast);
        v_asteroides.erase(std::remove(v_asteroides.begin(),v_asteroides.end(),ast),v_asteroides.end());
        sonido->stop();
        sonido->setMedia(QUrl("qrc:/multimedia/explosion1.mp3"));
        sonido->play();
        //std::cout << "eliminado" <<std::endl;
    }
}

//std::cout << "tamaño : " <<v_asteroides.size() << std::endl;
mundo->advance();
mundo->update();}

however the object that is supposed to be removed from the screen remains there (still) without disappearing.

1 Answers1

0

The error is that : for (xx : vs_) and vs_.erase can not be used together. You should use the iter returned by v_asteroides.erase(xxx) for the next loop.

use next code as suggested:

auto iter = vs_.begin();
    for (; iter != vs_.end(); )
    {
        //if need erase
        {
            //other logic code
            // mundo->removeItem(*iter);
            iter = vs_.erase(iter);  // at last row         
        }
        // else
        {
            //++iter;
        }

    }
  • thanks for the reply. effectively the way you propose to delete works correctly. but the world-> removeItem (item) "apparently" deletes the element as it no longer interacts with the objects. but it continues to be seen on screen in the place where it was "destroyed" – Julian Guillermo Zapata Rugele Jan 09 '21 at 15:25
  • The scene doesn't delete the item. it just remove item from the scene. see the document written by Qt."Removes the item item and all its children from the scene. The ownership of item is passed on to the caller (i.e., QGraphicsScene will no longer delete item when destroyed)." – Derek Zheng Jan 11 '21 at 01:38