gpt4 book ai didi

c++ - QGraphicsItem::toGraphicsObject() 在由 QGraphicsPixmapItem 派生的自己的类中返回 0

转载 作者:太空宇宙 更新时间:2023-11-04 09:50:33 24 4
gpt4 key购买 nike

目前,我正在尝试从我自己的 QGraphicsView 中获取由 :QObject 和 :QGraphicsPixmapItem 派生的项目。所以我在我的场景中添加了 2 个项目,现在我希望这些项目以另一种方法使用 QList <QGraphicsItem*> 将它们取出来。但不幸的是它不能很好地工作并且QGraphicsItem::toGraphicsObject()返回 0。

所以我在 Qt-Reference-Documentation 中找到了这个描述:

QGraphicsObject * QGraphicsItem::toGraphicsObject ()

Return the graphics item cast to a QGraphicsObject, if the class is actually a
graphics object, 0 otherwise.

因为我想为我想从 itemList 中取出的项目设置动画想要 setTargetObject对于 myAnimation .但是这个方法需要一个 QGraphicsObject所以这就是为什么我需要将其转换为。希望我的源代码能说明更多信息:

-- 啊--

class A : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
Q_PROPERTY (QPointF pos READ pos WRITE setPos)

public:
A()
{
setTransformationMode (Qt::SmoothTransformation);
}

QPointF itemPos;
};

-- A.cpp--

void A::method()
{
QList <QGraphicsItem*> itemList = myGraphicsView -> items();

QGraphicsObject *test = itemList.at (0) -> toGraphicsObject();

qDebug() << test; // <-- QGraphicsObject(0)

myAnimation -> setTargetObject (test);
myAnimation -> setPropertyName ("pos");
myAnimation -> setStartValue (QPointF (0, 100));
myAnimation -> setEndValue (QPointF (60, 100));

myAnimation -> start();
}

最佳答案

首先,QGraphicsObject 本身就是一个特定的类。您不能从 QObject 和任何 QGraphicsItems 创建新类并将其用作 QGraphicsObject。两者甚至不在同一个类层次结构中。所以你不能将一个转换到另一个。

其次,setTargetObject 采用QObject,而不是QGraphicsObject。所以你可以这样得到你的对象,它是一个QObject:

A *test = dynamic_cast<A*>(itemList.at(0));

setTargetObject 会欣然接受。

关于c++ - QGraphicsItem::toGraphicsObject() 在由 QGraphicsPixmapItem 派生的自己的类中返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11650068/

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