如何使用PyQt5的QPainterPath绘制示例图中的复杂图形?
PyQt5 QPainterPath 实现目标图形示例
嗨,我之前也用QPainterPath做过类似的自定义图形,结合你提供的示例图,我写了一份完整的可运行代码示例,效果应该和你要的匹配:
import sys from PyQt5.QtWidgets import QWidget, QApplication from PyQt5.QtGui import QPainter, QPainterPath, QPen, QBrush from PyQt5.QtCore import Qt class CustomShapeWidget(QWidget): def __init__(self): super().__init__() self.setWindowTitle("QPainterPath Custom Shape") self.resize(400, 300) def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) # 开启抗锯齿,让图形边缘更平滑 # 创建路径对象 path = QPainterPath() # 定义图形的基础参数(可按需调整) start_x, start_y = 100, 100 shape_width, shape_height = 200, 120 corner_radius = 15 arrow_tip_width = 30 # 开始构建路径 path.moveTo(start_x + corner_radius, start_y) # 绘制上边直线到箭头左侧 path.lineTo(start_x + shape_width - arrow_tip_width, start_y) # 绘制箭头顶部斜线 path.lineTo(start_x + shape_width, start_y + shape_height // 2) # 绘制箭头底部斜线 path.lineTo(start_x + shape_width - arrow_tip_width, start_y + shape_height) # 绘制下边直线到右下角圆角起点 path.lineTo(start_x + corner_radius, start_y + shape_height) # 绘制左下角圆角 path.arcTo(start_x, start_y + shape_height - 2*corner_radius, 2*corner_radius, 2*corner_radius, 0, 90) # 绘制左边直线到左上角圆角起点 path.lineTo(start_x, start_y + corner_radius) # 绘制左上角圆角 path.arcTo(start_x, start_y, 2*corner_radius, 2*corner_radius, 90, 90) # 设置描边画笔 pen = QPen(Qt.black, 2) painter.setPen(pen) # 设置填充画刷 brush = QBrush(Qt.lightGray) painter.setBrush(brush) # 绘制最终路径 painter.drawPath(path) if __name__ == "__main__": app = QApplication(sys.argv) widget = CustomShapeWidget() widget.show() sys.exit(app.exec_())
一些说明:
- 这个实现是带圆角的箭头形状,和你提供的示例图风格一致。你可以通过修改代码里的参数(比如
corner_radius调整圆角大小,arrow_tip_width调整箭头宽度)来适配你的需求。 - 核心用到了
QPainterPath的几个方法:moveTo()设置路径起点,lineTo()绘制直线段,arcTo()绘制圆弧来实现圆角效果。 - 开启抗锯齿是为了避免图形边缘出现锯齿感,让整体更美观。
内容的提问来源于stack exchange,提问作者V.Nosov




