Skip to content

Instantly share code, notes, and snippets.

@wention
Last active August 24, 2023 01:34
Show Gist options
  • Save wention/294425ce6d2ebc6040579c662ef3dcba to your computer and use it in GitHub Desktop.
Save wention/294425ce6d2ebc6040579c662ef3dcba to your computer and use it in GitHub Desktop.
Draw Half Rounded Rectangle Using PyQt5
def draw_rounded_rect(self, painter, rect, x_radius=10, y_radius=10, corners=(1, 1, 1, 1), mode = Qt.AbsoluteSize):
path = QPainterPath()
if mode == Qt.RelativeSize:
x_radius = x_radius / 100 * (rect.width()/2)
y_radius = y_radius / 100 * (rect.height()/2)
x_radius = max(0, min(x_radius, rect.width()/2))
y_radius = max(0, min(y_radius, rect.height()/2))
arc_rect = QRectF(0, 0, x_radius*2, y_radius*2)
angles = (180, 90, 0, 270)
points = (rect.topLeft(), rect.topRight(), rect.bottomRight(), rect.bottomLeft())
center_points = (arc_rect, arc_rect, rect.bottomLeft(), rect.bottomRight())
if corners[0] == 1:
arc_rect.moveTopLeft(rect.topLeft())
path.arcMoveTo(arc_rect, angles[0])
path.arcTo(arc_rect, angles[0], -90)
else:
path.moveTo(points[0])
if corners[1] == 1:
arc_rect.moveTopRight(rect.topRight())
path.arcTo(arc_rect, angles[1], -90)
else:
path.lineTo(points[1])
if corners[2] == 1:
arc_rect.moveBottomRight(rect.bottomRight())
path.arcTo(arc_rect, angles[2], -90)
else:
path.lineTo(points[2])
if corners[3] == 1:
arc_rect.moveBottomLeft(rect.bottomLeft())
path.arcTo(arc_rect, angles[3], -90)
else:
path.lineTo(points[3])
path.closeSubpath()
return path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment