QGraphicsItem执行鼠标事件完如何发送给QGraphicsView C++
时间: 2023-10-29 10:10:54 浏览: 29
可以通过在`QGraphicsItem`中重写`mousePressEvent()`、`mouseMoveEvent()`和`mouseReleaseEvent()`等事件函数来获取鼠标事件,然后使用`QGraphicsScene`的`sendEvent()`函数将事件发送给`QGraphicsView`。
具体步骤如下:
1. 在`QGraphicsItem`的子类中重写鼠标事件函数,例如:
```cpp
void MyItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
// 处理鼠标按下事件
}
```
2. 在`QGraphicsScene`中重写`event()`函数,捕获`QGraphicsItem`发出的鼠标事件,并发送给`QGraphicsView`,例如:
```cpp
bool MyScene::event(QEvent *event)
{
if (event->type() == QEvent::GraphicsSceneMousePress ||
event->type() == QEvent::GraphicsSceneMouseMove ||
event->type() == QEvent::GraphicsSceneMouseRelease)
{
QGraphicsSceneMouseEvent *mouseEvent = static_cast<QGraphicsSceneMouseEvent *>(event);
QApplication::sendEvent(view(), mouseEvent);
return true;
}
return QGraphicsScene::event(event);
}
```
3. 接着,在`QGraphicsView`的子类中重写鼠标事件函数,例如:
```cpp
void MyView::mousePressEvent(QMouseEvent *event)
{
// 处理鼠标按下事件
}
```
这样,当`QGraphicsItem`中的鼠标事件触发时,事件会被发送给`QGraphicsView`进行处理。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)