[问题记录]Qt QGraphicsItem 移动时出现残影

目录

1.问题现象

2.问题原因

3.修改方案


1.问题现象

自定义 QGraphicsItem 时,绘制rect,对象移动时出现残影。

2.问题原因

直接原因是view未刷新的问题,所以网上有人使用方案 setViewportUpdateMode(QGraphicsView::FullViewportUpdate); 的方案,但当图片过多时,此方案会造成画面闪烁,耗费资源等问题。

而根本原因是,boundingRect返回大小的问题,存在两种情况:

(1)boundingRect 返回的大小,不能完全包含实际图形大小,导致刷新不全

(2)boundingRect的左上角顶点位置、长宽,未补全画笔宽度,导致原因同(1)

boundingRect函数功能,是将图形项的外部边界定义为一个矩形。所有的绘图操作都必须限制在图形的边界矩形中,QGraphicsView需要使用这个边界来确定重绘的区域。

而边界的宽度,精确为画笔宽度的的一半。

3.修改方案

boundingRect的左上角顶点,需要补充画笔宽度/2,实际矩形的长宽,补全画笔宽度

cpp 复制代码
QRectF CGraphicsDragItem::boundingRect() const
{
    return QRectF(
        -m_penWidth/2,
        -m_penWidth/2,
        m_rectWidth+m_penWidth,
        m_rectHeight+m_penWidth);
}

void CGraphicsDragItem::paint(
    QPainter *painter,
    const QStyleOptionGraphicsItem *option,
    QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    if (hasFocus() || !collidingItems().isEmpty())
    {
        m_penWidth = 10;
        painter->setPen(QPen(QColor(255, 255, 255, 200), m_penWidth));
        if (hasFocus())
        {
            for (auto it : collidingItems())
            {
                it->update();
            }
        }
    }
    else
    {
        m_penWidth = 1;
        painter->setPen(QPen(QColor(100, 100, 100, 100), m_penWidth));
    }

    painter->setBrush(m_clrBrush);
    painter->drawEllipse(0, 0, m_rectWidth, m_rectHeight);
}
相关推荐
Do_It_Today1 小时前
php xml 入门学习资料
开发语言·php
熊猫钓鱼>_>1 小时前
Kotlin Multiplatform for OpenHarmony 实战:为 Landscapist 实现图片加载适配
开发语言·kotlin·华为云·ai编程·harmonyos·鸿蒙·openharmony
Nebula_g2 小时前
JavaSE加强:Commons-io框架
java·开发语言·算法·javase
Do_It_Today2 小时前
php url路由入门实例
开发语言·php
小羊没烦恼!2 小时前
关于大型asp.net应用系统的架构-架构的选择
java·服务器·开发语言·前端·c#
夏幻灵2 小时前
前端八股:JavaScript 深拷贝详解:实现方式、递归原理与循环引用
开发语言·前端·javascript
傲世仙尊3 小时前
C++起步-命名空间解决命名冲突与cin-cout缺省参数
开发语言·c++
hljqwb3 小时前
java服务异常日志只打印异常类型,没有堆栈定位分析(十)
java·开发语言
ym hyd 1113 小时前
生鲜超市库存管理信息系统源码 Java+SpringBoot+Vue3 前后分离
java·开发语言·vue.js·spring boot·毕设
haerapi3 小时前
KingbaseES 全文检索实战之前:先建立中文搜索的可解释基线
开发语言·python·全文检索