QGraphicsView 放大导致QGraphicsItem不更新

其实这个问题,原因是QGraphicsItem的boundingRect的范围不在当前的View范围内,当然不会刷新,特别是自定义的一些Item,特别要注意自己的boundingrect是否在准确的位置,所以其实是boundingrect没有自动更新位置导致的。

当遇到相似的问题时,不妨把boundingrect画出来就可以见分晓了。
下面是我们的代码:

#ifndef LIDARPOINTS_H
#define LIDARPOINTS_H


#include <QColor>
#include <QGraphicsItem>
#include <QImage>

class Lidarpoints : public QGraphicsItem
{
   
   
public:
    Lidarpoints(const QColor &color, int x, int y);
    Lidarpoints(/*const QImage image*/);

    void setLidarData(QPoint pos, std::vector<QPoint>& data);

    QRectF boundingRect() const Q_DECL_OVERRIDE;
    QPainterPath shape() const Q_DECL_OVERRIDE;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget) Q_DECL_OVERRIDE;



protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event) Q_DECL_OVERRIDE;
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event) Q_DECL_OVERRIDE;
    void mouseReleaseEvent(QGraphicsSceneMouseEvent 
在使用 `QGraphicsView` 时,如果重写了 `paintEvent` 方法但仍无法响应鼠标事件,可能是因为某些设置或操作干扰了事件的正常传递。以下是一些可能的原因和解决方法: ### 检查 `QGraphicsItem` 的鼠标事件响应设置 如果自定义的 `QGraphicsItem` 没有正确设置鼠标事件响应,可能导致鼠标事件无法被触发。确保调用 `setAcceptedMouseButtons()` 方法,并传入适当的鼠标按键标志。例如: ```cpp setAcceptedMouseButtons(Qt::LeftButton); ``` 如果此设置无效,还需检查是否在其他地方设置了冲突的属性,例如 `ItemIgnoresTransformations` 标志,该标志可能会影响某些交互行为的正常执行 [^3]。 ### 确保 `QGraphicsView` 的事件处理未被覆盖或忽略 如果重写了 `QGraphicsView` 的 `paintEvent` 方法,但未调用基类的实现,可能导致某些内部状态未正确更新,从而影响鼠标事件的处理。确保在重写的方法中调用基类的 `paintEvent`: ```cpp void MyGraphicsView::paintEvent(QPaintEvent *event) { // 自定义绘制逻辑 ... QGraphicsView::paintEvent(event); // 调用基类方法 } ``` ### 处理拖放事件 如果涉及拖放操作,可以重写 `dragLeaveEvent` 方法以确保拖动操作的完整性。例如: ```cpp void MyGraphicsView::dragLeaveEvent(QDragLeaveEvent *event) { // 处理拖出视图的逻辑 ... QGraphicsView::dragLeaveEvent(event); // 调用基类方法 } ``` ### 鼠标事件传递问题 如果某些图或视图的父级控件拦截了鼠标事件,可能导致事件无法到达目标对象。检查控件的层级结构,确保没有父级控件错误地处理了鼠标事件。此外,确保 `QGraphicsView` 和 `QGraphicsScene` 的交互配置正确,例如调用 `setMouseTracking(true)` 以启用鼠标追踪功能。 ### 示例代码:重写 `wheelEvent` 以支持缩放 如果需要通过鼠标滚轮控制视图的缩放,可以重写 `wheelEvent` 方法: ```cpp void MyGraphicsView::wheelEvent(QWheelEvent *event) { qreal scaleFactor = this->matrix().m11(); int wheelDeltaValue = event->delta(); if (wheelDeltaValue > 0) { this->scale(1.2, 1.2); // 放大 } else { this->scale(1.0 / 1.2, 1.0 / 1.2); // 缩小 } } ``` ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可峰科技

生活不易

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值