QPainterPath 不规则提示框

currentPosition()是最后一次绘制后的“结束点”(或初始点),使用moveTo()移动currentPosition()而不会添加任何元素。

    QPainterPath ​合并:

    1、方法1:connectPath合并成一个路径,从第一个路径的最后一个点链接一条直线到第二个路径

    2、方法2:addPath添加一个新路径作为子闭合路径

测试截图如下:

图1 addPath演示
图2 connectPath演示

上代码:

准备工作,设置窗口背景透明、置顶、无边框

setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); setAttribute(Qt::WA_TranslucentBackground);

​QPainterPath rectPath;

rectPath.moveTo(50, 50);

rectPath.arcTo(0, 0, 50 * 2, 50 * 2, 180, 270);  

绘制四分之三椭圆,arcTo参数含义:前两个参数表示椭圆外接举行左上定点坐标​,第三和第四参数表示椭圆的宽和高,四五个参数表示绘制起始角度,参数六表示绘制总角度

QPainterPath rectPath2 = rectPath; 

复制一个新的闭合路径​,并偏移指定距离

rectPath2.translate(100, 100);   

rectPath2.connectPath(rectPath);  连接两个闭合路径

QLinearGradient linear(rect().topLeft(), rect().bottomRight());  构造一个刷子,设置刷子起始位置

linear.setColorAt(0, Qt::red); 

linear.setColorAt(0.5, Qt::green);  

linear.setColorAt(1, Qt::blue);   设置指定位置刷子颜色

painter.setPen(QPen(QColor(255, 255, 255, 0), 0, Qt::SolidLine,  Qt::FlatCap, Qt::RoundJoin));  设置画笔类型

painter.setBrush(linear);  

painter.fillRect(rect(), Qt::gray);   
填充窗口背景色 方便观察(实际开发中以白色为宜)

painter.drawPath(rectPath);  使用addPath/connectPath方式时  该行代码不需要,因为该路径已经被合并到rectPath2

painter.drawPath(rectPath2);绘制制定闭合路径

不规则提示框如下

图3 不规则提示框

代码如下

 1 QPainter painter(this);
 2 
 3 QPainterPath rectPath;   
 4 
 5 rectPath.addRoundRect(QRect(rect().width() / 8, rect().height() / 2        , rect().width() / 2, rect().height() / 2), 10);  
 6 
 7 QPainterPath triPath;  
 8 
 9 triPath.moveTo(0, 0);   
10 
11 triPath.lineTo(rect().width() / 4, rect().height() / 2);  
12 
13 triPath.lineTo(rect().width() / 8 * 3, rect().height() / 2);
14 
15 triPath.lineTo(0, 0);   
16 
17 rectPath.addPath(triPath);    添加子闭合路径
18 
19 QLinearGradient linear(rect().topLeft(), rect().bottomRight());   
20 
21 linear.setColorAt(0, Qt::red);   
22 
23 linear.setColorAt(0.5, Qt::green);   
24 
25 linear.setColorAt(1, Qt::blue);   
26 
27 painter.setPen(QPen(QColor(255, 255, 255, 0), 0, Qt::SolidLine,        Qt::FlatCap, Qt::RoundJoin));  
28 
29 painter.setBrush(linear);   
30 
31 painter.fillRect(rect(), Qt::gray);   
32 
33 painter.drawPath(rectPath);
View Code

 

最终效果​

图4 效果图
 图5 ui布局

​rectPath.addRoundRect(QRect(rect().width() / 8, rect().height() / 2

        , rect().width() / 8 * 7, rect().height() / 2), 10);

posted @ 2016-06-27 20:41  朝十晚八  阅读(4129)  评论(0编辑  收藏  举报

返回顶部