Qt - 到子类的无效转换
我正在使用图形视图框架绘制多边形。我用这个向场景添加了一个多边形:
QGraphicsPolygonItem *poly = scene->addPolygon(QPolygonF(vector_of_QPointF));
poly->setPos(some_point);
但我需要在图形项上实现一些自定义行为,例如选择、鼠标悬停指示器以及其他类似的内容。因此,我声明了一个继承 QGraphicsPolygonItem 的类:
#include <QGraphicsPolygonItem>
class GridHex : public QGraphicsPolygonItem
{
public:
GridHex(QGraphicsItem* parent = 0);
};
GridHex::GridHex(QGraphicsItem* parent) : QGraphicsPolygonItem(parent)
{
}
如您所见,到目前为止,对该类没有做太多事情。但是不应该用我的 GridHex 类替换 QGraphicsPolygonItem 吗?这会引发“从 'QGraphicsPolygonItem*' 到 'GridHex*' 的无效转换”错误:
GridHex* poly = scene->addPolygon(QPolygonF(vector_of_QPointF));
我做错了什么?
I'm drawing polygons using the Graphics View framework. I added a polygon to the scene with this:
QGraphicsPolygonItem *poly = scene->addPolygon(QPolygonF(vector_of_QPointF));
poly->setPos(some_point);
But I need to implement some custom behaviour like selection, mouse over indicator, and other similar stuff on the graphics item. So I declared a class that inherits QGraphicsPolygonItem:
#include <QGraphicsPolygonItem>
class GridHex : public QGraphicsPolygonItem
{
public:
GridHex(QGraphicsItem* parent = 0);
};
GridHex::GridHex(QGraphicsItem* parent) : QGraphicsPolygonItem(parent)
{
}
Not doing much with that class so far, as you can see. But shouldn't replacing QGraphicsPolygonItem with my GridHex class work? This is throwing a " invalid conversion from 'QGraphicsPolygonItem*' to 'GridHex*' " error:
GridHex* poly = scene->addPolygon(QPolygonF(vector_of_QPointF));
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,由于“切片”的原因,派生类的指针指向父类并不是一个好主意。我建议你这样做
Generally, it's not a good idea for a pointer of a derived class to point the parent, because of 'slicing'. I suggest you do this instead
我猜测 scene->addPolygon 正在返回一个 QGraphicsPolygonItem,它是您专业化的基类。您将需要动态转换,因为您只能通过向上而不是向下的层次结构来安全地进行转换。
编辑:虽然我的答案有助于解决您的转换问题,但您如何才能保证场景正在创建您的 GridHex 对象?您是否计划子类化场景对象并返回 GridHex 对象?
您的 QGraphicsScene 子类将重写 addPolygon 来执行以下操作:
I'm guessing scene->addPolygon is returning a QGraphicsPolygonItem, which is a base class of your specialization. You will need to dynamic cast since you can only do the conversion safely by going up the heirarchy rather than down.
EDIT: While my answer helps with your conversion issue, how can you guarantee that the scene is creating your GridHex objects? Are you planning to subclass the scene object as well to return your GridHex objects?
Your QGraphicsScene subclass would override addPolygon to do something like: