In this lesson we want to learn about Python PySide6 Draw Ellipse, in graphical user interfaces you may want to draw different shapes like circles, rectangles, polygons and ellipses to enhance the appearance of your application. PySide6 provides QPainter class to perform custom drawing operations on paint device. In this lesson, we will explore how to draw an ellipse using QPainter, to follow this lesson, you should have basic understanding of Python programming and the PySide6 library. if you are new to PySide6, you may want to check out some introductory tutorials before continuing, or go back to the course and check the previous lessons.
Drawing an Ellipse
To draw an ellipse using PySide6 you can use the drawEllipse method of the QPainter class. this is an example code that draws an ellipse on widget:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
from PySide6.QtCore import Qt from PySide6.QtGui import QColor, QPainter, QPen from PySide6.QtWidgets import QApplication, QWidget class Window(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setWindowTitle('Draw Ellipse - GeeksCoders.com') self.setGeometry(300, 300, 350, 250) self.show() def paintEvent(self, event): painter = QPainter(self) painter.setPen(QPen(QColor('blue'), 2, Qt.SolidLine)) painter.drawEllipse(50, 50, 200, 100) if __name__ == '__main__': app = QApplication([]) window = Window() app.exec() |
In this code we have created custom widget by subclassing QWidget and override its paintEvent method. Inside paintEvent method we have created QPainter object and set its pen to define the color, width and style of the ellipse’s border. after that we have used drawEllipse method of the QPainter object to draw the ellipse with the specified position (x, y) and size (width, height).
You can modify the x, y, width and height arguments of the drawEllipse method to adjust the position and size of the ellipse.
Run the complete code and this will be the result.
Final Thoughts
In this lesson we learned how to draw an ellipse using Python PySide6. by creating QPainter object and calling its drawEllipse method, we were able to draw an ellipse on widget with specified position and size. You can use this knowledge to draw other shapes and create more complex custom widgets in your PySide6 applications.