I have my own QGraphicsPixmapItem which consists of a QGraphicsPixmapItem and some additional attributes (like std::string name)
class MyQGraphicsPixmapItem : public QGraphicsPixmapItem { private: std::string name; ... public: MyQGraphicsPixmapItem(); explicit MyQGraphicsPixmapItem(const QPixmap &pixmap, std::string name, QGraphicsItem *parent = nullptr); std::string getname() const; ... }; And the constructor is like this :
MyQGraphicsPixmapItem::MyQGraphicsPixmapItem(const QPixmap &pixmap, std::string name, QGraphicsItem *parent) : QGraphicsPixmapItem(pixmap, parent), name(name){ ... } Here is the problem : I have a bunch of MyQGraphicsPixmapItem that I add in a QGraphicsScene. But when I use the method QGraphicsScene::itemAt(const QPointF &position, const QTransform &deviceTransform) const, it returns QGraphicsItem* (not MyQGraphicsPixmapItem*). So I suppose that I have to use a down-casting right ? But even after using the down casting like this :
MyQGraphicsPixmapItem* item = static_cast<MyQGraphicsPixmapItem*>(QGraphicsScene::itemAt(...)); std::cout << item->getName() << std::endl; it returns an empty string (like there was no this.name = name; as shown in the constructor).
In conclusion, I create a bunch of MyQGraphicsPixmapItem in a QGraphicsScene with the right name initialization (I tested it with std::cout during the creation of QGraphicsScene) but when I want to randomly select a QGraphicsItem and check what is his name, I use that QGraphicsScene::itemAt that sets back every time the std::string name to empty despite the down-casting. Also, I'm extremely sure that I'm pointing at the right MyQGraphicsPixmapItem with the right arguments (I've done some tests). I was also thinking about implementing the right "itemAt" in my class "MyScene" (which inherits, you guessed it, from "QGraphicsScene") but I would use type_casting again.
PS : Tell me if my question is well asked.
Sincerely yours
this.name = name. Firstly why don't you assign it in the initializer list? Secondly...thisis a pointer, so I would expectthis->name.:. You can doMyQGraphicsPixmapItem::MyQGraphicsPixmapItem(const QPixmap &pixmap, std::string name, QGraphicsItem *parent) : QGraphicsPixmapItem(pixmap, parent), name(name) {}Please see isocpp.org/wiki/faq/ctors#init-lists