Moomin
Moomin

Reputation: 1926

How to distinguish objects that inherits QGraphicsItems when stored on QGraphicsScene.selectedItems()

Here is the situation:

  1. There are two classess that inherits both QGraphicsItem and QObject - Car and Bike.
  2. There are several objects of each class visualized using QGraphicsScene myScene.
  3. At some point two of the objects are selected and are available via myScene.selectedItems()
  4. There are different behaviour defined for interaction Car - Car,Bike - Bike, Bike - Car.

Since QGraphicsItem does not inherits from QObject I cannot invoke metaObject()->className() on item during:

foreach(QGraphicsItem* item,this->scene.selectedItems())
{
    item->metaObject()->className(); --error 'class QGraphicsItem' has no member named 'metaObject'
}

It is possible to use QGraphicsItem::data but it requires setting performing setData(...) it when creating objects.

Q:Is there any way to get an information what kind of objects are present on selectedItems list (ideally using className()) so the correct interaction function will be used?

Upvotes: 1

Views: 1269

Answers (2)

Trass3r
Trass3r

Reputation: 6297

The Qt solution for that (which also works in the -no-rtti case) is to use qgraphicsitem_cast and implement type():

class CustomItem : public QGraphicsItem
{
   ...
   enum { Type = UserType + 1 };

   int type() const
   {
       // Enable the use of qgraphicsitem_cast with this item.
       return Type;
   }
   ...
};

Upvotes: 3

thuga
thuga

Reputation: 12931

Like Losiowaty said, you can use dynamic_cast.

Example:

QList<QGraphicsItem*> g_items = scene->selectedItems();
for(int i = 0; i < g_items.length(); i++)
{
    QObject *selected_object = dynamic_cast<QObject*>(g_items[i]);
    if(selected_object)
    {
        //do what you need to do
    }
}

You can also cast your selected items directly to your Car or Bike class.

Upvotes: 2

Related Questions