Line drawing keeps recreating on eachmousemove

Viewed 46

I am trying to implement line drawing in qt. I am using two events mouseClickEvent and mouseMoveEvent, however I am getting this unwanted effect, whenever I draw a line and move my mouse, the line keeps being recreated on each mouse move. Is there way I can avoid this somehow ?Can this be done with manipulating the image? Qt line-drawing functions are not allowed to be used for this.

enter image description here

void MyWindow::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        x0 = event->x();
        y0 = event->y();
 
    }
    update();
}
void MyWindow::mouseMoveEvent(QMouseEvent *event)
{
    x1 = event->x();
    y1 = event->y();

    unsigned char *image;
    image = img->bits();
    
    ...line drawing algorithm
}
std::vector<std::pair<int, int>> myPair;

void MyWindow::drawPoints(unsigned char *image, int x, int y)
{
    myPair.push_back({x, y});
//Trying to clear previous line
    image[width*4*myPair[b].second + 4*myPair[b].first] = 0;
    image[width*4*myPair[b].second + 4*myPair[b].first + 1] = 0;
    image[width*4*myPair[b].second + 4*myPair[b].first + 2] = 0;
//Below draws white line
    image[width*4*y + 4*x] = 255;
    image[width*4*y + 4*x + 1] = 255;
    image[width*4*y + 4*x + 2] = 255;
}
1 Answers

You should store all objects you want to draw in a vector. A dedicated draw function can then clear the background and redraw everything you need/want. All other functions will then just add to or remove from the vector

Related