1

情况如下:

  1. 有两个类同时继承QGraphicsItemQObject-CarBike
  2. 每个类都有几个对象使用QGraphicsScene myScene.
  3. 在某些时候,两个对象被选中并且可以通过myScene.selectedItems()
  4. 为交互Car - Car, Bike - Bike,定义了不同的行为Bike - Car

由于QGraphicsItem不继承自我QObject无法metaObject()->className()在以下期间调用项目:

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

可以使用QGraphicsItem::data,但需要setData(...)在创建对象时设置执行它。

问:有什么方法可以获取selectedItems列表中存在哪些对象的信息(理想情况下使用className()),以便使用正确的交互功能?

4

2 回答 2

3

Qt 解决方案(也适用于 -no-rtti 情况)是使用 qgraphicsitem_cast 并实现 type()

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

   int type() const
   {
       // Enable the use of qgraphicsitem_cast with this item.
       return Type;
   }
   ...
};
于 2013-09-26T11:30:48.807 回答
2

就像 Losiowaty 说的,你可以使用 dynamic_cast。

例子:

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
    }
}

您还可以将所选项目直接投射到您的班级CarBike班级。

于 2013-05-22T12:26:49.773 回答