当鼠标光标在图形项中时,我想要更改它(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,有一个简单的方法来改变光标吗?
发布于 2017-06-19 16:50:26
您可能可以使用悬停事件。
在你的类构造函数中确保你做了..。
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:回答.
我有指南针在我的整个边框,我怎么能把面积缩小到我的绘图(在这种情况下,一个圆)?
重写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做类似的事情。)
发布于 2018-03-22 17:54:50
QGraphicsItem已经有了一种更改游标的方法,因此不需要手动处理悬停事件:
QGraphicsItem::setCursor(const QCursor &cursor)http://doc.qt.io/qt-5/qgraphicsitem.html#setCursor
PS:您所做的QWidget和QGraphicsItem的双重继承也是个坏主意,只继承QGraphicsItem。
https://stackoverflow.com/questions/44635760
复制相似问题