3

I am looking for a way to apply a horizontal opacity gradient when painting QLine elements using QPainter. Put simply, I want to be able to have the line opacity decrease the further away from the line center it is being painted. The effect I want to achieve corresponds to what a lot of image editing tools comonly describe as hardness of a brush.

Here is a sample image that compares a line using a hard brush to a soft one:

soft and hard line brush

This would be a minimum example for painting a regular QLine:

QPainter p;
p.setPen(QPen(Qt::black, 12, Qt::SolidLine, Qt::RoundCap));
p.drawLine(QPointF(0,0), QPointF(1024,1024));

How and where would I configure the line hardness I am describing? Is there something like a fall-off property when painting QLine elements?

In the docs I could only find examples for how to apply linear gradients between set points, which is not what I am looking for.

Basti Vagabond
  • 1,458
  • 1
  • 18
  • 26

1 Answers1

3

That's not QPen painting, that's brush painting, like in say photoshop, and Qt doesn't really support such functionality out of the box.

But it is quite easy to implement, you need a brush stencil pixmap, and you simply draw that pixmap on your target paint device along a line at a given step.

The line interpolation part is already answered here.

It is recommended that the brush stencil is an 8 bit grayscale QImage, then you can easily get a colorized version of that by using the greyscale value as an alpha value for the solid color of choice. QImage is preferable, as it offers individual pixel access. This allows to have any type of brush aside from hard and soft, including certain artistic brushes.

Naturally, if all you need is a soft brush, you can generate that directly in the desired color by utilizing Qt's existing gradients and skip the stencil colorizing part. You can use QPainter to procedurally draw colorizable or full color stencils to use as a brush.

dtech
  • 47,916
  • 17
  • 112
  • 190
  • Thanks! That sounds reasonable. I got another answer from the Qt forum, which I will also give a shot. https://forum.qt.io/topic/90841/qpainter-drawing-lines-configuring-line-softness-horizontal-opacity-gradient I'll edit my post as soon as I have some results. – Basti Vagabond May 18 '18 at 13:39