QWidget gets scratched under another QWidget

25 Views Asked by At

I subclassed QWidget and overwrite it's paintEvent() , I just draw a rounded rectangle.And I also overwrite the mousePressEvent ,mouseMoveEvent,mouseReleaseEvent, to make sure my Rectangle (which is my class name) can be dragged by mouse. That is it, I did nothing more, just draw a rectangle and make sure it is draggable. Then I create 2 Rectangle and show them in a parent QWidget. They are shown and can be moved, everything looks fine. But when I drag one rectangle above another , the rectangle below painted this blurry gray edge surrounding my dragging rectangle, and after I drag my rectangle away, a scratch left on the rectangle below. what is the problem.

I added some debug in the paintEvent function, it seems like when I drag one Rectangle over another,the paintEvent function is executed in both Rectangle

the image is my result when I drag my pink rectangle,the blue one gets a scratch

//here are my codes, very simple actually
#include "Rectangle.h"
#include <QPainter>
#include <QPaintEvent>
#include <QDebug>
Rectangle::Rectangle(const QString & name,QWidget *parent) : QWidget(parent),mColorName(name)
{
    mPressing = false;
}
void Rectangle::mousePressEvent(QMouseEvent* e){
    mPressing = true;
    mPressPos = e->pos();
}
void Rectangle::mouseReleaseEvent(QMouseEvent*){
    mPressing = false;
}
void Rectangle::mouseMoveEvent(QMouseEvent* e){
    if(!e) return;
    if(!mPressing) {
        return;
    }
    auto pos = mapToParent(e->pos()) - mPressPos;
    move(pos);
}
void Rectangle::paintEvent(QPaintEvent *e){
    if(!e) return;
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(mColorName));
    const auto rect = e->rect();
    painter.drawRoundedRect(rect,8,8);
    qDebug() << "drawing rect:" << rect << ",name:" << mColorName;
}

0

There are 0 best solutions below