0

I have created a class Atom that extends the Qt class QGraphicsItem like this:

Atom::Atom(qreal rad, qreal mass, int element, int state) : QGraphicsItem()
{
    // Initialization code
}
void Atom::changeState(int newState)
{
    // Code...
}

Then, I add my atom to the scene like this:

Atom *a=new Atom(rad,mass,element,state);
a->setPos(pos);
scene->addItem(a);

However, Qt converts my Atom class to a QGraphicsItem class. Now, when I call scene->items(), I get a QList of QGraphicsItems, which do not have the properties and methods of my Atom class.

So, I am asking the question: How would I go about getting a list of the Atoms that I have added to my QGraphicsScene?

Thanks.

Joel
  • 2,654
  • 6
  • 31
  • 46

2 Answers2

2

You'll need to cast the QGraphicsItems to Atoms. Please see this question for details:

Subclassing QGraphicsItem prevents me from being able to use itemAt() on a QGraphicsScene/View

Community
  • 1
  • 1
Anthony
  • 8,570
  • 3
  • 38
  • 46
1

No. Your items are not converted to anything. They are still of your custom type. In C++, all objects of a derived class are also of class they derive from. Nothing is converted so nothing is lost.

Do a dynamic_cast<Atom*>(item) and you will get your item back.

Stephen Chu
  • 12,724
  • 1
  • 35
  • 46
  • Thanks. What is the difference between: `dynamic_cast(item)` vs `((Atom*)item)`? – Joel Feb 05 '12 at 20:30
  • @Joel: http://stackoverflow.com/questions/28002/regular-cast-vs-static-cast-vs-dynamic-cast – Mat Feb 05 '12 at 20:36