Accessing methods of a subclassed QGraphicsRectItem object

I have subclassed the QGraphicsRectItem, named ResizableRectItem. I have added a new member (int index), and two methods (getIndex() and setIndex() ). I'm adding ResizableRectItems to a QGraphicsScene

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

Later i have to call the getIndex() method, but i only access the items over the items() of the scene(), but

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

is incorrect, because scene()->items() is QGraphicsItem and don't have getIndex() method. What is the correct solution ? Thanks!

Answers


What is the correct solution?

If you can re-think the logic in your code so that you don't have to depend on the interface of ResizableRectItem, that will be best.

If you cannot do that, then, you'll need to use dynamic_cast.

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

You can try to cast the object to your datatype and on success operate on it. Like that:

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

More Info at http://doc.qt.io/qt-5/metaobjects.html


Need Your Help

Appwidget size calculation

android android-4.0-ice-cream-sandwich android-3.0-honeycomb android-appwidget android-2.3-gingerbread

It might be me, but when I calculate minimum app widget sizes according to the formula given on the android page I don't get the right widget widths; The formula is as follows:

Build Array in Excel VBA

arrays excel vba excel-vba

Desired result: The result would be a function that builds an array of values from column B. The values are restricted by having the same value in column A. 'E.g. Column A value = 1 myArray = (0,1,...