QGraphicsItem不接收鼠标悬停事件。

时间:2020-12-10 20:24:12

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):

我有一个来自QGraphicsView的类,它包含qgraphicsitem-派生元素。我希望这些元素在鼠标光标悬停的时候改变颜色,所以我实现了hoverEnterEvent(和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?

不过,没有运气。我做错了什么?

2 个解决方案

#1


22  

Fixed it. I need to use setAcceptHoverEvents(true) in the constructor of my QGraphicsItem-derived class.

固定它。我需要在qgraphicsitem-派生类的构造函数中使用setAcceptHoverEvents(true)。

#2


1  

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

在我的例子中,如果我在QGraphicsView类的实现中重写了mouseMoveEvent,那么鼠标悬停事件就不起作用了。我通过添加一个调用来解决这个问题。

QGraphicsView::mouseMoveEvent(event);

which propagated the event to the parent, which in turn sent it out to all the scene items.

它将事件传播给父进程,然后将其发送到所有场景项。

#1


22  

Fixed it. I need to use setAcceptHoverEvents(true) in the constructor of my QGraphicsItem-derived class.

固定它。我需要在qgraphicsitem-派生类的构造函数中使用setAcceptHoverEvents(true)。

#2


1  

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

在我的例子中,如果我在QGraphicsView类的实现中重写了mouseMoveEvent,那么鼠标悬停事件就不起作用了。我通过添加一个调用来解决这个问题。

QGraphicsView::mouseMoveEvent(event);

which propagated the event to the parent, which in turn sent it out to all the scene items.

它将事件传播给父进程,然后将其发送到所有场景项。