Example QLinearGradient to create a 3-D shadow effect
Qt Graphics View Lesson 2 |
Example using QLinearGradient (QGradient) to create a 3-D shadow effect
Download the complete project zip file
![]() |
In this example, I wanted to creat a 3-D shadow effect around my simple box. I used the QGradient class to create the background shadow, then drew another rounded-rect over that, offset by 3 pixels.
The class StateBox is the widget that represents the box in the scene. Its derived from the QGraphicsItem. MainWindow.cpp creates the scene and inserts a StateBox object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
// example of a drop shadow effect on a box, using QLinearGradient and two boxes void StateBox::paint (QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { /* The drop shadow effect will be created by drawing a filled, rounded corner rectangle with a gradient fill. Then on top of this will be drawn filled, rounded corner rectangle, filled with a solid color, and offset such that the gradient filled box is only visible below for a few pixels on two edges. The total box size is _width by _height. So the top box will start at (0,0) and go to (_width-shadowThickness, _height-shadowThickness), while the under box will be offset, and start at (shadowThickness+0, shadowThickness+0) and go to (_width, _height). */ int shadowThickness = 3; QLinearGradient gradient; gradient.setStart(0,0); gradient.setFinalStop(_width,0); QColor grey1(150,150,150,125);// starting color of the gradient - can play with the starting color and ,point since its not visible anyway // grey2 is ending color of the gradient - this is what will show up as the shadow. the last parameter is the alpha blend, its set // to 125 allowing a mix of th color and and the background, making more realistic shadow effect. QColor grey2(225,225,225,125); gradient.setColorAt((qreal)0, grey1 ); gradient.setColorAt((qreal)1, grey2 ); QBrush brush(gradient); painter->setBrush( brush); // for the desired effect, no border will be drawn, and because a brush was set, the drawRoundRect will fill the box with the gradient brush. _outterborderPen.setStyle(Qt::NoPen); painter->setPen(_outterborderPen); QPointF topLeft (shadowThickness+0, shadowThickness+0); QPointF bottomRight ( _width, _height); QRectF rect (topLeft, bottomRight); painter->drawRoundRect(rect,25,25); // corner radius of 25 pixels // draw the top box, the visible one QBrush brush2(QColor(255,250,200,255),Qt::SolidPattern); painter->setBrush( brush2); QPointF topLeft2 (0, 0); QPointF bottomRight2 ( _width-shadowThickness, _height-shadowThickness); QRectF rect2 (topLeft2, bottomRight2); painter->drawRoundRect(rect2,25,25); } |
Trackback this post | Subscribe to the comments via RSS Feed