Solved QGraphicsScene/QGraphicsView & QGradient
-
Hello,
I intend to draw inside a QGraphicsScene a "life gauge", that is a rectangle whose length varies depending on your hit/life points. The user should be able to change their own hit/life points and the gauge should adapt nicely, matching the new value entered by the user.
I would like to draw that gauge with a gradient (orange -> red for example), but I'm not sure what's the best way to do that. I've done some quick research and it looks like I could use a QPainter and make the appropriate QImage, which could then be converted to a QPixmap, and drawn into the QGraphicsScene/QGraphicsView.
But wouldn't that be rather costly if I change the gauge via QPropertyAnimations? If for example I were to change the length of the gauge from 250 to 200 pixels within 1 second, Qt would probably decrease the length one by one (249, 248, 247, ...202, 201, 200) and as a result the setter that I specified with the property would be called 50 times, resulting in Qt using 50 times a QPainter.
So basically my question is: do you know a better/smarter way to change the length of a gradiented rectangle?
-
Hi,
What about implementing your own QGraphicsItem and re-implement the paint method ? Depending on the geometry of your gauge, QGraphicsRectItem could also be used.
Hope it helps
-
@SGaist thanks for replying.
I'm not familiar with re-implementing paint yet :S Could you drop a very short example? For example if I wanted to paint an entirely black rectangle, what would that look like? I'll probably manage to take it from here afterward.
-
It should be something like:
void GaugeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->setPen(Qt::black); painter->setBrush(Qt::black); painter->drawRect(boundingRect()); }
-
Thanks a lot SGaist :)