currentPosition()是最后一次绘制后的“结束点”(或初始点),使用moveTo()移动currentPosition()而不会添加任何元素。
QPainterPath 合并:
1、方法1:connectPath合并成一个路径,从第一个路径的最后一个点链接一条直线到第二个路径
2、方法2:addPath添加一个新路径作为子闭合路径
测试截图如下:
上代码:
准备工作,设置窗口背景透明、置顶、无边框
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);绘制制定闭合路径
不规则提示框如下
不规则提示框
代码如下
QPainter painter(this); QPainterPath rectPath; rectPath.addRoundRect(QRect(rect().width() / , rect().height() / , rect().width() / , rect().height() / ), ); QPainterPath triPath; triPath.moveTo(, ); triPath.lineTo(rect().width() / , rect().height() / ); triPath.lineTo(rect().width() / * , rect().height() / ); triPath.lineTo(, ); rectPath.addPath(triPath); 添加子闭合路径 QLinearGradient linear(rect().topLeft(), rect().bottomRight()); linear.setColorAt(, Qt::red); linear.setColorAt(0.5, Qt::green); linear.setColorAt(, Qt::blue); painter.setPen(QPen(QColor(, , , ), , Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); painter.setBrush(linear); painter.fillRect(rect(), Qt::gray); painter.drawPath(rectPath);
最终效果
效果图
ui布局
rectPath.addRoundRect(QRect(rect().width() / 8,
rect().height() / 2
, rect().width() / 8 * 7, rect().height() / 2),
10);