1. 绘制图形
[cpp] view plain copy
- protected:
- void paintEvent(QPaintEvent *);
- void Widget::paintEvent((QPaintEvent *event)
- {
- QPainter painter(this); //this为绘图设备,即表明在该部件上进行绘制
- painter.drawLine(QPaint(0, 0), QPaint(100, 100));
- }
QPainter painter(this); // 会立即开始在设备上绘制,自动调用begin()函数,然后析构函数中调用end()函数结束绘制。
QPainter painter;// 不带参数时,可以在后面调用QPainter::begin(QPaintDevice *device)来指定绘制设置,然后用完再调用end()函数。
等价于
[cpp] view plain copy
- void Widget::paintEvent((QPaintEvent *event)
- {
- QPainter painter;
- painter.begin(this);
- painter.drawLine(QPaint(0, 0), QPaint(100, 100));
- painter.end();
- }
2. 使用画刷
画刷可以设置颜色和填充模式
[cpp] view plain copy
- QBrush brush(QColor(0,0,255), Qt::Dense4Pattern);
- painter.setBrush(brush);
3. 使用画笔
[cpp] view plain copy
- //参数为:画刷,线宽,画笔风格,画笔端点,画笔连接风格
- QPen pen(Qt::green, 5, Qt::DotLine, Qt::RoundCap, Qt::RoundJoin);
- painter.setPen(pen);
4. 绘制矩形
[cpp] view plain copy
- painter.drawRect(0, 0, 100, 80); //x,y,w,h
5. 绘制椭圆(圆)
[cpp] view plain copy
- painter.drawEllipse(0, 0, 100, 80); //x,y,w,h
6. 绘制圆弧
[cpp] view plain copy
- QRectF rect(70.0, 40.0, 80.0, 60.0); //x,y,w,h
- int startAngle = 30 * 16; //值为,实际角度 * 16
- int spanAngle = 120 * 16;
- //三个参数:rect表示弧线所在的矩形,startAngle起始角度,spanAngle跨越角度
- painter.drawArc(rect, startAngle, spanAngle);
7. 绘制扇形
[cpp] view plain copy
- QRectF rect_top(20.0, 20.0, 100.0, 100.0);
- // 扇形起始角度
- int startAngle = 0 * 16;
- // 扇形覆盖范围(120度的)
- int spanAngle = 120 * 16;
- painter.drawPie(rect_top, startAngle, spanAngle);
8. 绘制多边形
[cpp] view plain copy
- QPolygon pts;
- pts.setPoints(3, -1,0, 1,0, 0,39); //第一个参数表示3个点,后面是三个点坐标
- painter.drawConvexPolygon(pts);
9. 绘制路径
[cpp] view plain copy
- QPainterPath path;
- path.addEllipse(-4, -4, 8, 8);//添加一个圆
- path.addRect(-5, -5, 10, 10); //添加一个矩形
- painter.drawPath(path);
10. 绘制圆环
根据以上的填充规则,可以得到绘制圆环的一个方便的方法
[cpp] view plain copy
- QPainterPath path;
- path.addEllipse(0,0,100,100);
- path.addEllipse(25,25,50,50);
- painter.setBrush(Qt::blue);
- path.setFillRule(Qt::OddEventFil);//使用奇偶填充,刚好可以只显示圆环
- painter.drawPath(path);
11. 填充与擦除
[cpp] view plain copy
- //使用画刷填充一个矩形区域
- painter.fillRect(QRect(10,100,150,20), QBrush(Qt::darkYellow));
- //擦除一个矩形区域的内容
- painter.eraserRect(QRect(50,0,50,120));