I am trying to understand how it is possible to redefine the way items are selected and transformed (once selected) in a QGraphicsScene
. For example changing length of a line, move a line, change a polygon by moving one of its points.
I have created a child of QGraphicsView
and have started to overload its mousePressEvent
, but it seems that the selection and move actions are captured by QGraphicsItem
. How can I override it as they are protected and not visible from a child of QGraphicsView
?
I can imagine I need to overload QGraphicsItem::mousePressEvent
in a myGraphicsItem
, but then it means I have to also overload the QGraphicsScene
for handling myGraphicsItem
? And how do I handle the selected item position in a scene when it gets moved?
Are there any examples I could look at?
I am (clearly) a bit lost.
UPDATE: Based on the feedback I have created a child of QGraphicsItems
as follows:
class baseGraphicItem : public QGraphicsItem
{
public:
explicit baseGraphicItem(QVector<QPoint> data, operationType shape, QObject * parent = 0);
signals:
public slots:
public:
virtual QRectF boundingRect() const;
virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0);
QPainterPath shape() const;
virtual void hoverEnterEvent ( QGraphicsSceneHoverEvent * event );
virtual void hoverLeaveEvent ( QGraphicsSceneHoverEvent * event );
private:
QPolygon vertex;
operationType shapeType;
};
baseGraphicItem::baseGraphicItem(QVector<QPoint> data, operationType shape, QObject *parent) :
QGraphicsItem(), vertex(data), shapeType(shape)
{
qDebug() << vertex;
this->setAcceptHoverEvents(false);
}
These are for the paint, boundingRect
and shape.
void baseGraphicItem::paint(QPainter * painter, const QStyleOptionGraphicsItem*, QWidget*)
{
int i=0;
// Following needs better code for polygons
do painter->drawLine(vertex.at(i), vertex.at(i+1));
while (i++<vertex.size()-2);
}
QRectF baseGraphicItem::boundingRect() const
{
return vertex.boundingRect();
}
QPainterPath baseGraphicItem::shape() const
{
QPainterPath path;
path.addPolygon(vertex);
return path;
}
Unfortunately, the selection works well with one line or polygon. But when a line is inside a polygon, it is almost always selecting the polygon instead of the line. Is this because of the boundingRect
or the shape? Also how can I get the new coordinates stored in my QPolygon
vertex?
Thanks