QGraphicsItem执行鼠标事件完如何发送给QGraphicsView C++
时间: 2023-10-29 18:07:57 浏览: 25
在Qt中,QGraphicsView类继承自QAbstractScrollArea,而QGraphicsItem类是QGraphicsScene中的一个元素,因此,要将QGraphicsItem的鼠标事件发送给QGraphicsView,需要使用以下步骤:
1. 在QGraphicsItem的鼠标事件处理函数中,通过scene()函数获取该item所在的QGraphicsScene对象。
2. 通过scene()函数获取QGraphicsScene对象之后,可以使用views()函数获取该场景中所有的视图对象列表。
3. 遍历视图对象列表,对于每个视图对象,可以通过mapFromScene()函数将场景坐标转换为视图坐标,然后使用itemAt()函数判断该坐标是否在当前item的范围内。如果在范围内,则可以将事件传递给视图对象。
以下是一个示例代码片段:
```cpp
void MyGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mousePressEvent(event);
QGraphicsScene *scene = this->scene();
QList<QGraphicsView*> views = scene->views();
foreach(QGraphicsView* view, views)
{
QPointF pos = view->mapFromScene(event->scenePos());
if(this == view->itemAt(pos))
{
QMouseEvent *newEvent = new QMouseEvent(event->type(), pos, event->button(), event->buttons(), event->modifiers());
QCoreApplication::postEvent(view, newEvent);
break;
}
}
}
```
在这个示例中,我们将QGraphicsItem的鼠标事件传递给了它所在的QGraphicsView。注意,这里使用了QCoreApplication的postEvent()函数来将事件发送给视图对象。