访问子类 QGraphicsRectItem 对象的方法

Accessing methods of a subclassed QGraphicsRectItem object

我已经将 QGraphicsRectItem 子类化,命名为 ResizableRectItem。我添加了一个新成员(int index)和两个方法(getIndex() 和 setIndex())。 我正在将 ResizableRectItems 添加到 QGraphicsScene

ResizableRectItem* item1 = new ResizableRectItem(selrect.normalized());
scene()->addItem(item1);

稍后我必须调用 getIndex() 方法,但我只能访问 scene() 的 items() 上的项目,但是

int idx = scene()->items().at(0)->getIndex();

不正确,因为 scene()->items() 是 QGraphicsItem 并且没有 getIndex() 方法。 什么是正确的解决方案? 谢谢!

您可以尝试将对象转换为您的数据类型,并在成功后对其进行操作。像这样:

ResizableRectItem* item = qobject_cast<ResizableRectItem*>(scene()->items().at(0)); 
if (item)
{
   int idx = item->getIndex();
}

更多信息请见http://doc.qt.io/qt-5/metaobjects.html

What is the correct solution?

如果你能重新考虑代码中的逻辑,这样你就不必依赖ResizableRectItem的接口,那就最好了。

如果您不能这样做,那么,您将需要使用 dynamic_cast

QGraphicsRectItem* gitem = scene()->items().at(0);
ResizableRectItem* item = dynamic_cast<ResizableRectItem*>(gitem);
if ( item != nullptr )
{
   int idx = item->getIndex();
}