QT 基本图形绘制

1. 绘制图形

[cpp] view plain copy

  1. protected:  
  2.     void paintEvent(QPaintEvent *);  
  3.   
  4. void Widget::paintEvent((QPaintEvent *event)  
  5. {  
  6.     QPainter painter(this); //this为绘图设备,即表明在该部件上进行绘制  
  7.     painter.drawLine(QPaint(0, 0), QPaint(100, 100));  
  8. }  

QPainter painter(this); // 会立即开始在设备上绘制,自动调用begin()函数,然后析构函数中调用end()函数结束绘制。
QPainter painter;// 不带参数时,可以在后面调用QPainter::begin(QPaintDevice *device)来指定绘制设置,然后用完再调用end()函数。

等价于

[cpp] view plain copy

  1. void Widget::paintEvent((QPaintEvent *event)  
  2. {  
  3.     QPainter painter;  
  4.     painter.begin(this);  
  5.     painter.drawLine(QPaint(0, 0), QPaint(100, 100));  
  6.     painter.end();  
  7. }  

2. 使用画刷
画刷可以设置颜色和填充模式

[cpp] view plain copy

  1. QBrush brush(QColor(0,0,255), Qt::Dense4Pattern);  
  2. painter.setBrush(brush);  

3. 使用画笔

[cpp] view plain copy

  1. //参数为:画刷,线宽,画笔风格,画笔端点,画笔连接风格  
  2. QPen pen(Qt::green, 5, Qt::DotLine, Qt::RoundCap, Qt::RoundJoin);  
  3. painter.setPen(pen);  

4. 绘制矩形

[cpp] view plain copy

  1. painter.drawRect(0, 0, 100, 80); //x,y,w,h  

5. 绘制椭圆(圆)

[cpp] view plain copy

  1. painter.drawEllipse(0, 0, 100, 80); //x,y,w,h  

6. 绘制圆弧

[cpp] view plain copy

  1. QRectF rect(70.0, 40.0, 80.0, 60.0); //x,y,w,h  
  2. int startAngle = 30 * 16; //值为,实际角度 * 16  
  3. int spanAngle = 120 * 16;  
  4.   
  5. //三个参数:rect表示弧线所在的矩形,startAngle起始角度,spanAngle跨越角度  
  6. painter.drawArc(rect, startAngle, spanAngle);  


7. 绘制扇形

[cpp] view plain copy

  1. QRectF rect_top(20.0, 20.0, 100.0, 100.0);  
  2.   
  3. // 扇形起始角度  
  4. int startAngle = 0 * 16;  
  5. // 扇形覆盖范围(120度的)  
  6. int spanAngle = 120 * 16;  
  7. painter.drawPie(rect_top, startAngle, spanAngle);  

8. 绘制多边形

[cpp] view plain copy

  1. QPolygon pts;  
  2. pts.setPoints(3, -1,0, 1,0, 0,39); //第一个参数表示3个点,后面是三个点坐标  
  3. painter.drawConvexPolygon(pts);  

9. 绘制路径

[cpp] view plain copy

  1. QPainterPath path;  
  2. path.addEllipse(-4, -4, 8, 8);//添加一个圆  
  3. path.addRect(-5, -5, 10, 10); //添加一个矩形  
  4. painter.drawPath(path); 


10. 绘制圆环
根据以上的填充规则,可以得到绘制圆环的一个方便的方法

[cpp] view plain copy

  1. QPainterPath path;  
  2. path.addEllipse(0,0,100,100);  
  3. path.addEllipse(25,25,50,50);  
  4. painter.setBrush(Qt::blue);  
  5. path.setFillRule(Qt::OddEventFil);//使用奇偶填充,刚好可以只显示圆环  
  6. painter.drawPath(path);  

11. 填充与擦除

[cpp] view plain copy

  1. //使用画刷填充一个矩形区域  
  2. painter.fillRect(QRect(10,100,150,20), QBrush(Qt::darkYellow));  
  3.   
  4. //擦除一个矩形区域的内容  
  5. painter.eraserRect(QRect(50,0,50,120));  
  6.  
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值