Search code examples
qtinheritanceqgraphicsviewqgraphicsitem

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 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?


Solution

  • 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);