我想在图形项中更改鼠标光标(MyCircle继承自QObject
和QGraphicsItem
(。如果我的类继承自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);
然后覆盖hoverEnterEvent
并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);
}
作为旁注:你真的继承了QObject
和QGraphicsItem
吗? 如果是这样,您可能可以通过简单地从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
做类似的事情。