在 QObject - QGraphicsItem 继承类中更改鼠标光标



我想在图形项中更改鼠标光标(MyCircle继承自QObjectQGraphicsItem(。如果我的类继承自QWidget,我会重新实现enterEvent()leaveEvent()并按如下方式使用它:

MyCircle::MyCircle(QObject *parent)
    : QWidget(parent), QGraphicsItem() // But I can't
{
    rect = QRect(-100,-100,200,200);
    connect(this,SIGNAL(mouseEntered()),this,SLOT(in()));
    connect(this,SIGNAL(mouseLeft()),this,SLOT(out()));
}
void MyCircle::in()
{
    QApplication::setOverrideCursor(Qt::PointingHandCursor);
}
void MyCircle::out()
{
    QApplication::setOverrideCursor(Qt::ArrowCursor);
}
void MyCircle::enterEvent(QEvent *)
{
    emit mouseEntered();
}
void MyCircle::leaveEvent(QEvent *)
{
    emit mouseLeft();
}

不幸的是,我需要为那个圆圈制作动画(它实际上是一个按钮(,所以我需要 QObject,有没有一种简单的方法来更改光标?

QGraphicsItem已经有了一个改变光标的方法,所以你不需要手动玩弄悬停事件:

QGraphicsItem::setCursor(const QCursor &cursor)

http://doc.qt.io/qt-5/qgraphicsitem.html#setCursor

PS:QWidget和你做的QGraphicsItem双重继承也是一个坏主意,只能从QGraphicsItem继承。

您可能可以使用悬停事件。

在你的类构造函数中,确保你做...

setAcceptHoverEvents(true);

然后覆盖hoverEnterEventhoverLeaveEvent

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

作为旁注:你真的继承了QObjectQGraphicsItem吗? 如果是这样,您可能可以通过简单地从QGraphicsObject继承来实现相同的目标。

编辑1:回答...

在整个边界矩形中有指向的手 icone,我怎么能 仅将区域缩小到我的绘图(在本例中为圆(?

重写QGraphicsItem::shape以返回表示实际形状的QPainterPath...

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

现在覆盖QGraphicsItem::hoverMoveEvent以使用 shape 方法...

virtual void hoverMoveEvent (QGraphicsSceneHoverEvent *event) override
{
  QGraphicsItem::hoverMoveEvent(event);
  if (shape().contains(event->pos())) {
    QApplication::setOverrideCursor(Qt::PointingHandCursor);
  } else {
    QApplication::setOverrideCursor(Qt::ArrowCursor);
  }
}

显然,上述内容可能会对性能产生影响,具体取决于绘制形状的复杂性,因此QPainterPath

(注意:与其使用QGraphicsItem::shape不如用QGraphicsItem::opaque做类似的事情。

最新更新