【问题标题】:How to distinguish objects that inherits QGraphicsItems when stored on QGraphicsScene.selectedItems()存储在 QGraphicsScene.selectedItems() 上时如何区分继承 QGraphicsItems 的对象
【发布时间】:2013-05-22 12:13:15
【问题描述】:

情况如下:

  1. 有两个类同时继承了QGraphicsItemQObject - CarBike
  2. 使用QGraphicsScene myScene 可视化每个类的多个对象。
  3. 有时两个对象被选中,可通过myScene.selectedItems()获得
  4. 为交互Car - CarBike - BikeBike - 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()),以便使用正确的交互函数?

【问题讨论】:

  • 为什么“setData(...)”不是一个可行的选择?或者,您可以尝试 dynamic_casts。您也不能使用 metaObject 信息,因为“item”是 QGraphicsItem 类型,但由于您的类也继承自 QObject,因此将 item 转换为 QObject* 并使用存储在那里的信息应该是安全的。

标签: c++ qt qt4 multiple-inheritance


【解决方案1】:

Qt 解决方案(也适用于 -no-rtti 情况)是使用 qgraphicsitem_cast 和 implement type():

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

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

【讨论】:

    【解决方案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 班级。

    【讨论】:

    • 这需要使用 RTTI 构建 Qt,这对于一个琐碎的用例来说意味着很多麻烦。
    • 如果它实际上是您想要的类型,它不会执行任何检查。
    • @Trass3r 是的。我不知道我在想什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多