Nominate our 2022 Qt Champions!

[SOLVED] QGraphicsScene and Persistent References

  • I apologize if this has been asked already -- if it has, I couldn't find it. At any rate -- is it ok/possible to store a persistent references (pointers) to objects inside a QGraphicsScene? For example, if I create a QGraphicsSimpleTextItem, and add it to a QGraphicsScene myScene, like so:

    QGraphicsSimpleTextItem *myItem = new QGraphicsSimpleTextItem(QString("@"));

    If, later on in this code, more objects are added/removed from myScene, myItem or other objects are moved, modified, etc., is there ever a scenario where the myItem pointer could become invalid (assuming the pointer stays in scope)? If so, is there a good/accepted way to store a persistent reference to objects in a QGraphicsScene?

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Adding new objects won't change the memory address of older objects nor moving them on the scene etc.

    Depending on what you need these pointers for you can use one of Qt's containers like QVector/QList/QMap/QHash/QSet or if you only need to keep one item, a simple member variable would be enough.

Log in to reply