I would like to change my mouse cursor when it is in a graphics item (MyCircle inherits from QObject
and QGraphicsItem
).
Had my class inherited from <
QGraphicsItem
already has a method for changing the cursor, so you don't need to manually play around with hover events:
QGraphicsItem::setCursor(const QCursor &cursor)
http://doc.qt.io/qt-5/qgraphicsitem.html#setCursor
PS: The dual inheritance of QWidget
and QGraphicsItem
you do is also a bad idea, only inherit from QGraphicsItem
.
You can probably use hover events.
In your class constructor make sure you do...
setAcceptHoverEvents(true);
Then override hoverEnterEvent and hoverLeaveEvent.
virtual void hoverEnterEvent (QGraphicsSceneHoverEvent *event) override
{
QGraphicsItem::hoverEnterEvent(event);
QApplication::setOverrideCursor(Qt::PointingHandCursor);
}
virtual void hoverLeaveEvent (QGraphicsSceneHoverEvent *event) override
{
QGraphicsItem::hoverLeaveEvent(event);
QApplication::setOverrideCursor(Qt::ArrowCursor);
}
As a side note: do you actually inherit from both QObject
and QGraphicsItem
? If so, you could probably achieve the same goal by simply inheriting from QGraphicsObject.
Edit 1: In answer to...
I have the pointing hand icone in my whole bounding rect, how can I reduce the area only to my drawing (in this case a circle) ?
Override QGraphicsItem::shape to return a QPainterPath
representing the actual shape...
virtual QPainterPath shape () const override
{
QPainterPath path;
/*
* Update path to represent the area in which you want
* the mouse pointer to change. This will probably be
* based on the code in your 'paint' method.
*/
return(path);
}
Now override QGraphicsItem::hoverMoveEvent to make use of the shape
method...
virtual void hoverMoveEvent (QGraphicsSceneHoverEvent *event) override
{
QGraphicsItem::hoverMoveEvent(event);
if (shape().contains(event->pos())) {
QApplication::setOverrideCursor(Qt::PointingHandCursor);
} else {
QApplication::setOverrideCursor(Qt::ArrowCursor);
}
}
The above could, obviously, have an impact on performance depending on the complexity of the shape drawn and, hence, the QPainterPath
.
(Note: rather than using QGraphicsItem::shape
you could do a similar thing with QGraphicsItem::opaque instead.)