先执行QGraphicsItem鼠标事件再执行QGraphicsView鼠标事件 C++
时间: 2023-09-11 07:08:11 浏览: 50
可以通过重写QGraphicsItem的mousePressEvent、mouseMoveEvent和mouseReleaseEvent来实现先执行QGraphicsItem鼠标事件再执行QGraphicsView鼠标事件。在重写这些事件时,调用父类的对应事件函数即可让其继续处理该事件,示例代码如下:
```cpp
void MyGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
// 处理QGraphicsItem的鼠标事件
// ...
// 调用父类的鼠标事件函数,让其继续处理该事件
QGraphicsItem::mousePressEvent(event);
}
void MyGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
// 处理QGraphicsItem的鼠标事件
// ...
// 调用父类的鼠标事件函数,让其继续处理该事件
QGraphicsItem::mouseMoveEvent(event);
}
void MyGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
// 处理QGraphicsItem的鼠标事件
// ...
// 调用父类的鼠标事件函数,让其继续处理该事件
QGraphicsItem::mouseReleaseEvent(event);
}
```
在重写QGraphicsView的鼠标事件时,也要调用父类的对应事件函数,示例代码如下:
```cpp
void MyGraphicsView::mousePressEvent(QMouseEvent *event)
{
// 先判断是否有QGraphicsItem处理了该事件
if (itemAt(event->pos()) != nullptr)
return;
// 处理QGraphicsView的鼠标事件
// ...
// 调用父类的鼠标事件函数,让其继续处理该事件
QGraphicsView::mousePressEvent(event);
}
void MyGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
// 先判断是否有QGraphicsItem处理了该事件
if (itemAt(event->pos()) != nullptr)
return;
// 处理QGraphicsView的鼠标事件
// ...
// 调用父类的鼠标事件函数,让其继续处理该事件
QGraphicsView::mouseMoveEvent(event);
}
void MyGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
// 先判断是否有QGraphicsItem处理了该事件
if (itemAt(event->pos()) != nullptr)
return;
// 处理QGraphicsView的鼠标事件
// ...
// 调用父类的鼠标事件函数,让其继续处理该事件
QGraphicsView::mouseReleaseEvent(event);
}
```
这样,当鼠标事件发生在QGraphicsItem上时,会先执行QGraphicsItem的鼠标事件函数,然后再执行QGraphicsView的鼠标事件函数;当鼠标事件发生在QGraphicsView上时,会先判断是否有QGraphicsItem处理了该事件,如果没有则执行QGraphicsView的鼠标事件函数。
相关推荐
![](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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)