gpt4 book ai didi

c++ - 如何区分存储在 QGraphicsScene.selectedItems() 上时继承 QGraphicsItems 的对象

转载 作者:太空宇宙 更新时间:2023-11-04 16:21:12 26 4
gpt4 key购买 nike

情况是这样的:

  1. 有两个类继承了 QGraphicsItemQObject - CarBike
  2. 使用 QGraphicsScene myScene 可视化每个类的几个对象。
  3. 在某些时候,其中两个对象被选中并可通过 myScene.selectedItems()
  4. 使用
  5. 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()),以便正确的交互函数是用过吗?

最佳答案

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

关于c++ - 如何区分存储在 QGraphicsScene.selectedItems() 上时继承 QGraphicsItems 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16691451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com