views:

78

answers:

2

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?

A: 

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);
Extrakun
Thanks for the slicing tip.
David McDavidson
In the case you showed, wouldn't my GridHex object be sliced, since QGraphicsScene::addItem() receives a QGraphicsItem as parameter?
David McDavidson
A: 

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);
SB
Oh right, I guess I'm doing everything wrong here. I'm still kinda familiarizing myself with the framework. Haven't thought of subclassing QGraphicsScene before, but thats what I'll have to do.
David McDavidson
So if I want to add custom items to a scene, I gotta subclass QGraphicsScene to be able to accept my custom items? How should I set a QGraphicsScene subclass to be able to add my custom items to it?
David McDavidson