问题描述
当鼠标光标位于图形项目中时,我想更改鼠标光标(MyCircle 继承自 QObject
和 QGraphicsItem
).如果我的类继承自 QWidget
,我会重新实现 enterEvent()
和 leaveEvent()
并按如下方式使用它:
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 QWidget
, I would have reimplemented enterEvent()
and leaveEvent()
and use it as follows :
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,有没有一种简单的方法可以更改光标?
Unfortunately, I need to animate that circle (it's a button actually), so I need QObject, is there an easy way to change the cursor ?
推荐答案
你或许可以使用 悬停事件.
在你的类构造函数中确保你做...
In your class constructor make sure you do...
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代码>
.
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
.
编辑 1:为了回答...
我的整个边界矩形中有指向手图标,我怎么能仅将区域缩小到我的绘图(在本例中为圆形)?
覆盖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
方法...
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);
}
}
显然,根据绘制的形状的复杂性以及QPainterPath
,上述内容可能会对性能产生影响.
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.)
这篇关于在 QObject 中更改鼠标光标 - QGraphicsItem 继承类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!