[PyQt] Access to QBrush gradient

Phil Thompson phil at riverbankcomputing.com
Sun Apr 26 09:34:59 BST 2020


On 26/04/2020 07:42, Maurizio Berti wrote:
> Hello,
> 
> 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 
> be
> 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 
> QBrush.
> The problem is that QBrush.gradient() just returns a basic QGradient, 
> and
> not the actual gradient class used in its construction.
> The result is that you won't be able to access the gradient functions 
> (for
> example, the angle of a conical gradient) since it obviously results in 
> an
> AttributeError:
> 
>>>> grad = QtGui.QConicalGradient(.5, .5, 225)
>>>> brush = QtGui.QBrush(grad)
>>>> brush.gradient().angle()
> AttributeError: 'QGradient' object has no attribute 'angle'
>>>> brush.gradient()
> <PyQt5.QtGui.QGradient at 0x7f941a28c2d0>
>>>> brush.gradient().type() == QtGui.QGradient.ConicalGradient
> True
> 
> 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 
> related
> to performance).
> 
> After closely looking at the sources of QBrush again, though, I 
> realized
> 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)
>>>> brushGrad.angle()
> 225.0
> 
> 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.
> 
> Maurizio

I can fix that so the conversion is done automatically.

Thanks,
Phil


More information about the PyQt mailing list