代码演示:
#include <QPainter>
MyDraw::MyDraw(QWidget *parent) :QWidget(parent)
{QLinearGradient linearGradient(0,0,400,400);linearGradient.setColorAt(0.0,Qt::white);linearGradient.setColorAt(0.2,QColor(0,0,0));linearGradient.setColorAt(1.0,Qt::black);linearGradient.setSpread(Qt::PadSpread);brush = linearGradient; pen = QPen(QColor(0,0,0),1,Qt::SolidLine,Qt::FlatCap,Qt::MiterJoin);setPalette(QPalette(Qt::white));setAutoFillBackground(true);setMinimumSize(400,400);
}
void MyDraw::paintEvent(QPaintEvent *)
{QPainter p(this);p.setPen(pen);p.setBrush(brush);QRect rect(50,100,300,200);static const QPoint points[4]={QPoint(150,100),QPoint(300,150),QPoint(350,250),QPoint(100,300)};int startAngle =30*16;int spanAngle =120*16;QPainterPath path;path.addRect(150,150,100,100);path.moveTo(100,100);path.cubicTo(300,100,200,200,300,300);path.cubicTo(100,300,200,200,100,100);path.setFillRule(fillRule);p.drawLine(rect.topLeft(),rect.bottomRight());//直线p.drawRect(rect); //长方形p.drawRoundRect(rect);//圆角方形p.drawEllipse(rect); //椭圆形p.drawPolygon(points,4); //多边形p.drawPolyline(points,4);//多边线p.drawPoints(points,4);//点p.drawArc(rect,startAngle,spanAngle);//弧p.drawPath(path); //路径p.drawText(rect,Qt::AlignCenter,tr("Hello Qt!")); //文字p.drawPixmap(150,150,QPixmap("butterfly.png"));//图片
}
运行效果演示: