开发者

Qt - invalid conversion to child class

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 inhe开发者_开发技巧rits 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?


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

GridHex* hex = new GridHex(scene);
scene->addItem(hex);


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.

GridHex* poly = dynamic_cast<GridHex*>(scene->addPolygon(QPolygonF(vector_of_QPointF)));
if (poly != NULL) {
    // You have a gridhex!
}

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:

// Call the base class
QGraphicsPolygonItem* result = QGraphicsScene::addPolygon(vectorOfPoints);
// Return your stuff
return new GridHex(result);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜