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);繪制制定閉合路徑
不規則提示框如下
代碼如下

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);
最終效果
rectPath.addRoundRect(QRect(rect().width() / 8, rect().height() / 2
, rect().width() / 8 * 7, rect().height() / 2), 10);