简体   繁体   English

Qt将扩展的QGraphicsItem添加到场景

[英]Qt add extended QGraphicsItem to scene

I have created a class Atom that extends the Qt class QGraphicsItem like this: 我创建了一个类Atom ,它扩展了Qt类QGraphicsItem如下所示:

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. 但是,Qt将我的Atom类转换为QGraphicsItem类。 Now, when I call scene->items() , I get a QList of QGraphicsItems, which do not have the properties and methods of my Atom class. 现在,当我调用scene->items() ,我得到一个QGraphicsItems的QList,它没有我的Atom类的属性和方法。

So, I am asking the question: How would I go about getting a list of the Atoms that I have added to my QGraphicsScene? 因此,我问一个问题:我将如何获取已添加到QGraphicsScene中的Atom列表?

Thanks. 谢谢。

You'll need to cast the QGraphicsItems to Atoms. 您需要将QGraphicsItems转换为Atoms。 Please see this question for details: 请查看此问题以获取详细信息:

Subclassing QGraphicsItem prevents me from being able to use itemAt() on a QGraphicsScene/View 子类化QGraphicsItem使我无法在QGraphicsScene / View上使用itemAt()

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. 在C ++中,派生类的所有对象也属于它们派生的类。 Nothing is converted so nothing is lost. 什么都不会转换,所以什么也不会丢失。

Do a dynamic_cast<Atom*>(item) and you will get your item back. 执行dynamic_cast<Atom*>(item) ,您将把您的物品取回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM