Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QGraphicsScene::addItem: item has already been added to this scene

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++;
    }
}
like image 941
medegor44 Avatar asked Oct 23 '25 04:10

medegor44


1 Answers

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.

like image 180
dtech Avatar answered Oct 25 '25 18:10

dtech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!