Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Drawing" with a totally transparent pen in QT

Tags:

c++

qt

qt5

I am writing a whiteboard application in QT. I am using a double layer approach, so I have a QPixmap that contains the drawing, and another that contains the background. The drawing pixmap is, unsurprisingly, with an alpha channel.

Now I wish to implement an eraser tool. This tool should revert, wherever it paints, the pixmap's color to QColor(255, 255, 255, 0) (i.e. - totally transparent). My method of painting, however, does not lend well to that.

This is my draw routine:

void WhiteBoardWidget::draw(QPointF pos, bool erase) {
    QPainter painter( &underlyingImage );
    QPen pen = painter.pen();

    if( ! erase ) {
        pen.setColor(penColor);
        pen.setWidth(penWidth);
    } else {
        pen.setColor( QColor(255, 255, 255, 0) );
        pen.setWidth(penWidth * EraserSizeFactor);
    }

    painter.setPen(pen);
    painter.drawLine( lastPoint, pos );
    lastPoint = pos;
    update();
}

I understand why it doesn't work (the transparent pen doesn't change the pixmap because it is, wait for it... transparent). I'm just not sure what would be a good way to do what I want.

like image 548
Shachar Shemesh Avatar asked Dec 20 '25 20:12

Shachar Shemesh


1 Answers

This is a matter of composition mode of the QPainter in use. Default is QPainter::CompositionMode_SourceOver, which, as current pen is transparent, just leaves the underground as is. By setting to QPainter::CompositionMode_Clear you enforce the painter to erase anything. You shouldn't even have to change the current pen's colour then.

like image 164
Aconcagua Avatar answered Dec 23 '25 08:12

Aconcagua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!