How do you draw graphics using PyQt5?
The method of drawing graphics in PyQt5 can be achieved by using the QPainter object. Below are some commonly used drawing methods:
- Drawing a line: Use the drawLine() method of QPainter to draw a straight line. You can specify the coordinates of the starting point and ending point of the line segment.
- Draw a rectangle: Use the drawRect() method of QPainter to draw a rectangle. You can specify the coordinates of the top left corner, width, and height of the rectangle.
- Draw an ellipse: Use the drawEllipse() method of QPainter to draw an ellipse. You can specify the outer bounding rectangle of the ellipse.
- Draw a polygon: use the drawPolygon() method of QPainter to draw a polygon. You can specify the coordinates of each vertex of the polygon.
- Draw an arc: Use the QPainter’s drawArc() method to draw an arc. You can specify the bounding rectangle of the arc, as well as the starting angle and sweep angle.
- Drawing Text: Use the drawText() method of QPainter to draw text. You can specify the position and content of the text.
These methods involve overriding the paintEvent() method on a custom QWidget or QMainWindow. Within the paintEvent() method, a QPainter object is created and used for drawing operations. Once the drawing is completed, the end() method is called to finish the drawing. For example:
class MyWidget(QWidget):
def paintEvent(self, event):
painter = QPainter(self)
painter.drawLine(10, 10, 100, 100)
painter.drawRect(50, 50, 100, 100)
painter.drawEllipse(50, 50, 100, 100)
points = [QPoint(50, 50), QPoint(100, 150), QPoint(150, 100)]
painter.drawPolygon(QPolygon(points))
painter.drawArc(50, 50, 100, 100, 0, 180)
painter.drawText(100, 100, "Hello PyQt5")
painter.end()
This way, you can draw various shapes on the QWidget.