4

I tried to add several items to QGraphicsScene, but after calling scene->addItem(new Bonus(Bonus::BonusType::coin, randPoint, pixels, parent)); in application output appears this message: QGraphicsScene::addItem: item has already been added to this scene.
What I do wrong?
Code:

for(int i = 0; i < coinsCount; ) {
    QPoint randPoint(random() % g->getWidth(),
                     random() % g->getHeight());

    if(g->getType(randPoint) != Graph::wall && !usedPoints.contains(randPoint)) {
        scene->addItem(new Bonus(Bonus::BonusType::coin, randPoint, pixels, parent));
        usedPoints.push_back(randPoint);
        i++;
    }
}
medegor44
  • 107
  • 1
  • 6

1 Answers1

8

You are passing a parent item. If the parent item is already added to the scene, setting it as a parent for the new item will add the latter to the scene as well.

The constructor runs before addItem() so by the time the latter is executed, the item is already in the scene.

Note that this implicitly adds this graphics item to the scene of the parent. You should not add the item to the scene yourself.

dtech
  • 47,916
  • 17
  • 112
  • 190