[PyQt] Access to QBrush gradient
phil at riverbankcomputing.com
Sun Apr 26 09:34:59 BST 2020
On 26/04/2020 07:42, Maurizio Berti wrote:
> this was meant to be a question, but after some thinking and testing, I
> found a solution for my doubt on my own, and since I believe it might
> helpful to know this, I thought it would be good to share it with you.
> I was trying to access (and, possibly, update) the gradient of a
> The problem is that QBrush.gradient() just returns a basic QGradient,
> not the actual gradient class used in its construction.
> The result is that you won't be able to access the gradient functions
> example, the angle of a conical gradient) since it obviously results in
>>>> grad = QtGui.QConicalGradient(.5, .5, 225)
>>>> brush = QtGui.QBrush(grad)
> AttributeError: 'QGradient' object has no attribute 'angle'
> <PyQt5.QtGui.QGradient at 0x7f941a28c2d0>
>>>> brush.gradient().type() == QtGui.QGradient.ConicalGradient
> By looking at the Qt C++ sources, gradient() just returns a standard
> QGradient indeed, "filled in" with the QBrush data, so it's not a PyQt
> issue: Qt just does that.
> I don't know if there's a specific reason for this (maybe something
> to performance).
> After closely looking at the sources of QBrush again, though, I
> that the gradient is "cast" when needed, so I gave it a try by using
> sip.cast; it works:
>>>> import sip
>>>> brushGrad = sip.cast(brush.gradient(), QtGui.QConicalGradient)
> Obviously you have to check the gradient().type() before, and cast the
> correct gradient afterwards, otherwise the values won't make much
> sense: in
> the case above a cast on a QLinearGradient will result in the finalStop
> having coordinates (255, 0).
> I hope this helps.
I can fix that so the conversion is done automatically.
More information about the PyQt