渐变有三种:QLinearGradient、QConicalGradient 、 QRadialGradient
它们都有一个QGradient父类
QGradient父类的常用公共函数有:
void QGradient::setSpread ( Spread method ); //设置填充梯度区域外的区域,参数有: // QGradient::PadSpread :填充区域内最接近的停止颜色。这是默认的。 // QGradient::RepeatSpread : 在区域外继续重复填充 // QGradient::ReflectSpread : 在区域外反射填充 QGradient::setCoordinateMode ( CoordinateMode mode ); //设置渐变的坐标模式,比如QGradient::LogicalMode设置坐标为逻辑坐标(默认为该值) void setColorAt ( qreal position, const QColor & color ); //设置梯度颜色, position处于0~1之间
QLinearGradient线性渐变
构造函数函数如下:
QLinearGradient ( qreal x1, qreal y1, qreal x2, qreal y2 ) //其中x1,y1表示渐变起始坐标, x2,y2表示渐变终点坐标 //如果只有x相等,则表示垂直线性渐变,如果只有y相等,则表示平行线性渐变,否则就是斜角线性渐变
示例1-垂直渐变:
void Widget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing,true); QLinearGradient Linear(100,100,100,200); //垂直渐变 Linear.setColorAt(0,Qt::red); Linear.setColorAt(1,Qt::blue); painter.setBrush(Linear); painter.setPen(Qt::transparent); painter.drawRect(100,100,100,100); //100,100 到200,200 }
示例2-水平渐变
void Widget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing,true); QLinearGradient Linear(100,100,200,100); //水平渐变 Linear.setColorAt(0,Qt::red); Linear.setColorAt(1,Qt::blue);
painter.setBrush(Linear); painter.setPen(Qt::transparent); painter.drawRect(100,100,100,100); //100,100 到200,200 }
QradialGradient半径渐变
更据圆的半径来设定不同的颜色
QRadialGradient ( qreal cx, qreal cy, qreal radius, qreal fx, qreal fy ); // cx cy : 设置圆的中心原点(center) // radius:设置圆半径 //fx fy : 设置焦点focus,也就是颜色的起始位置
示例1:
void Widget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing,true); painter.translate(width()/2,height()/2); QRadialGradient Radial(0,0,120,0,0); //设置圆的原点和焦点在中心,半径120 Radial.setColorAt(0,Qt::red); Radial.setColorAt(0.5,Qt::blue); //设置50%处的半径为蓝色 Radial.setColorAt(1,Qt::green); painter.setPen(Qt::transparent); painter.setBrush(Radial); painter.drawEllipse(-120,-120,240,240); }
示例2:
void Widget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing,true); painter.translate(width()/2,height()/2); QRadialGradient Radial(0,0,120,0,60); //设置焦点在(0,60),半径120 Radial.setColorAt(0,Qt::red); Radial.setColorAt(0.5,Qt::blue); Radial.setColorAt(1,Qt::green); painter.setPen(Qt::transparent); painter.setBrush(Radial); painter.drawEllipse(-120,-120,240,240); }
QConicalGradient圆锥渐变
构造函数如下所示:
QConicalGradient ( qreal cx, qreal cy, qreal angle ); //设置(cx,cy)位置为圆锥尖,设置angle角度为起始颜色位置(逆时针渐变)
示例:
void Widget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing,true); painter.translate(width()/2,height()/2); QConicalGradient Conical(0,0,30); //设置点在中心,角度为30 Conical.setColorAt(0,Qt::red); Conical.setColorAt(0.5,Qt::blue); Conical.setColorAt(1,Qt::green); painter.setPen(Qt::transparent); painter.setBrush(Conical); painter.drawEllipse(-120,-120,240,240); }
未完,下章来学习: