[问题记录]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);
}
相关推荐
余醉 | dtminer19 分钟前
56%的保护效应藏在乳腺密度里:Nat Commun 高分中介孟德尔随机化全 R 管线拆解(附核心图)
开发语言·r语言·孟德尔随机化
2501_9339232522 分钟前
SpringCloud组件:Eureka服务注册与发现
java·开发语言·后端·spring cloud·eureka
染指111041 分钟前
142.Agent-多Agent框架-通过Skills实现多Agent
开发语言·人工智能·python·langchain·agents
好好学习O(∩_∩)O1 小时前
[QT] 多线程moveToThread 和易踩的8个坑
开发语言·qt
我是人✓1 小时前
Java核心语法:作用域、循环与大数值处理
java·开发语言·后端
敲代码的乔帮主1 小时前
Python 3 现代类型标注入门
开发语言·python
‎ദ്ദിᵔ.˛.ᵔ₎2 小时前
c++11:fuction包装器
开发语言·c++
kimnoic2 小时前
Python 爬虫的原理
开发语言·python
Fluxproxy2 小时前
Python爬虫异步提速终极方案|线程池ThreadPoolExecutor实战,告别单线程慢速爬取
开发语言·爬虫·python
淡海水2 小时前
02-07-原理篇-GC暂停时间的本质
开发语言·unity·c#·gc·暂停时间