Search code examples
pythonpyqtpyqt5pysidepyside2

How to draw custom oval shape in PyQt?


So I have been trying to make a custom oval shape using QGraphicsEllipseItem.

Upon reading the Qt's official documentation regarding QGraphicsEllipseItem, I didn't seem to find out how to manage it.

Here is the custom oval shape:

enter image description here


Solution

  • If you want to implement complex shapes then a possible solution is to use QPainterPathItem:

    from PyQt5.QtCore import QRectF
    from PyQt5.QtGui import QColor, QPainterPath
    from PyQt5.QtWidgets import (
        QApplication,
        QGraphicsPathItem,
        QGraphicsScene,
        QGraphicsView,
    )
    
    
    def main():
        app = QApplication([])
    
        radius = 20
        length = 100
    
        square = QRectF(0, 0, 2 * radius, 2 * radius)
    
        path = QPainterPath()
        path.moveTo(radius, 0)
        path.arcTo(square, 90, 180)
        path.lineTo(length, 2 * radius)
        square.moveRight(length + 2 * radius)
        path.arcTo(square, -90, 180)
        path.lineTo(radius, 0)
    
        item = QGraphicsPathItem()
        item.setBrush(QColor("red"))
        item.setPen(QColor("green"))
        item.setPath(path)
    
        scene = QGraphicsScene()
        view = QGraphicsView(scene)
        scene.addItem(item)
        view.show()
    
        app.exec_()
    
    
    main()