Changing mouse cursor in a QObject - QGraphicsItem inherited class

后端 未结 2 960
时光取名叫无心
时光取名叫无心 2021-01-27 03:32

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 <

2条回答
  •  北海茫月
    2021-01-27 04:18

    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.)

提交回复
热议问题