View Full Version : Create my own QGradient subclass

6th September 2015, 10:48
I want to draw a polyline using QPainter. The line should change color dynamically according to point coordinates.

In order to achieve this, I'd like to subclass QGradient in order to obtain a QFunctionGradient where I can set a std::function<QColor(QPointF)> that gives me the color of a point given its coordinates.

So, at first, how It's possibile to draw a polyline with QPainter and color it according to a QGradient?

And it's possible to subclass QPainter and use this subclass inside QBrush?

6th September 2015, 20:59
The API for the actual formulae of gradients (radial, linear etc.) is not exposed publicly.
If it were, we would probably have something like a QAbstractGradient class with a set of protected virtual functions for us to reimplement with our own functionality.

In your situation, what I would do is first use a QPainter to render a white polyline (polished, with anti-aliasing etc.) onto a QImage, then obtain the QImage.bits() (http://doc.qt.io/qt-5/qimage.html#bits) pointer and go through every non-transparent pixel in the image, changing their colour based on a custom function, and preserving the alpha values.

The resulting QImage can then be QPainter-ed anywhere else.

Another technique: you can also generate a Qimage "by hand" (by setting each pixel), and then QPainting that coloured image on top of your polyline with the SourceIn composition mode (http://doc.qt.io/qt-5/qpainter.html#CompositionMode-enum).
So you have a map of your gradient and you're using the antialiased polyline as a soft mask.

7th September 2015, 21:58
Ok so it's how I was thinking, I must do this by myself... I'll try, thanks for your advices.