Search code examples
qtalphaqpainter

QPainter, prevent adding of alpha factors


I'm trying to draw a rectangle with QPainter. This is going well, but I noticed that if I set a pen and a brush on the painter with the same color, the alpha factor of the pen and the brush are added somehow. This causes the line drawn by the pen to apear less transparent. Is there anyway to prevent this addition of the colors? I would expect that if the pen and the brush are the same color the line drawn by the pen would be "invisible". Below the part of my code to draw the rectangle and an image of the output.

QBrush newbrush = QBrush(painter->brush());
newbrush.setColor(QColor(0, 0, 255, 125));
newbrush.setStyle(Qt::SolidPattern);
painter->setBrush(newbrush);

QPen newpen = QPen(painter->pen());
newpen.setColor(QColor(0, 0, 255, 125));
newpen.setWidth(10);
painter->setPen(newpen);

painter->drawRect(QRect(QPoint(100, 50), QPoint(500, 500)));

enter image description here


Solution

  • You will need to change the painter composition mode.

    QPainter::CompositionMode_SourceOver

    This is the default mode. The alpha of the source is used to blend the pixel on top of the destination.

    So check out the rest and see which one does it for you.

    As mentioned in the comment below, you will need to draw the fill and outline in a sequence in order for the compositing mode to kick in, as it seems like it is ignored then when you are drawing both in a single call. Drawing in sequence is not necessarily a performance overhead, just an extra line and some reordering in the code.