QGraphicsItem 不接收鼠标悬停事件
我有一个派生自 QGraphicsView
的类,其中包含 QGraphicsItem
派生的元素。我希望这些元素在鼠标光标悬停在它们上方时改变颜色,因此我实现了 hoverEnterEvent
(和 hoverLeaveEvent
):
void MyGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent* event)
{
update (boundingRect());
}
但是,此事件处理程序代码永远不会执行。我已经明确启用了鼠标跟踪:
MyGraphicsView::MyGraphicsView(MainView *parent) :
QGraphicsView(parent)
{
setMouseTracking(true);
viewport()->setMouseTracking(true);
...
}
仍然没有运气。我做错了什么?
I have a class derived from QGraphicsView
, which contains QGraphicsItem
-derived elements. I want these elements to change color whenever the mouse cursor hovers over them, so I implemented hoverEnterEvent
(and hoverLeaveEvent
):
void MyGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent* event)
{
update (boundingRect());
}
However, this event handler code is never executed. I've explicitly enabled mouse tracking:
MyGraphicsView::MyGraphicsView(MainView *parent) :
QGraphicsView(parent)
{
setMouseTracking(true);
viewport()->setMouseTracking(true);
...
}
Still, no luck. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
修好了。我需要在
QGraphicsItem
派生类的构造函数中使用setAcceptHoverEvents(true)
。Fixed it. I need to use
setAcceptHoverEvents(true)
in the constructor of myQGraphicsItem
-derived class.就我而言,如果我在 QGraphicsView 类的实现中覆盖 mouseMoveEvent ,悬停事件将不起作用。我通过添加一个调用来修复此问题,
该调用将事件传播到父级,然后父级将其发送到所有场景项目。
In my case, hover events wouldn't work if I overrode mouseMoveEvent in my implementation of the QGraphicsView class. I fixed this by adding a call to
which propagated the event to the parent, which in turn sent it out to all the scene items.