PyQt - Drawing a Triangle



A triangle is a two-dimensional closed figure which consists of three equal sides, angles, and, vertices. It is also known as a polygon.

triangle

Drawing a Triangle in PyQt

In PyQt, we have two main classes to draw a triangle − QPainter and QPainterPath. The QPainter class is known for low-level painting design that reduces the storage cost. A QPainterPath is an object i.e. constructed for filling, outlining, and clipping a triangle. The QPainterPath only calls through the drawPath() method. The main advantage of painter paths over normal drawing operations is their ability to draw complex shapes easily.

The path of QPainterPath can be added using various convenience methods such as lineTo() and moveTo().

  • The moveTo() method starts a new subpath and closes the previous one, without adding a component to the current position.
  • The lineTo() is also a collection of QPainter that sets the pairs of points to draw a triangle.

In this tutorial, we learn how to draw a triangle using PyQt.

  • Plain Triangle − A simple shape of triangle is known as Plain Triangle. To draw a triangle, we use the methods- moveTo() and lineTo() that follow the module QPainterPath.
  • Color Filled Triangle − The color filling concept is derived from the background color of any geometrical shape. Here, we use the method setBrush() to fill the color of a triangle.

Example 1

Following example shows the code snippet of QPainter object to draw a plain triangle using PyQt.

from PyQt6 import QtWidgets, QtCore
from PyQt6.QtGui import QPainter, QPainterPath
class MyWidget(QtWidgets.QWidget):
   def paintEvent(self, event):
      painter = QPainter()
      path = QPainterPath()
      painter.begin(self)
      painter.setRenderHint(QPainter.RenderHint.Antialiasing)
      painter.setPen(QtCore.Qt.GlobalColor.red)
      path.moveTo(100, 200)
      path.lineTo(200, 100)
      path.lineTo(300, 200)
      path.lineTo(100, 200)
      painter.drawPath(path)
app = QtWidgets.QApplication([])
widget = MyWidget()
widget.show()
app.exec()

Output

The above code produces the following output −

simple triangle

Example 2

Following example illustrates the triangle in a color-filled shape using PyQt.

from PyQt6 import QtWidgets, QtCore
from PyQt6.QtGui import QPainter, QPainterPath
class MyWidget(QtWidgets.QWidget):
   def paintEvent(self, event):
      painter = QPainter()
      path = QPainterPath()
      painter.begin(self)
      painter.setRenderHint(QPainter.RenderHint.Antialiasing)
      painter.setPen(QtCore.Qt.GlobalColor.green)
      painter.setBrush(QtCore.Qt.GlobalColor.gray)
      path.moveTo(200, 200)
      path.lineTo(300, 100)
      path.lineTo(300, 200)
      path.lineTo(100, 300)
      painter.drawPath(path)
app = QtWidgets.QApplication([])
widget = MyWidget()
widget.show()
app.exec()

Output

The above produces the following Output −

color filled rectangle
Advertisements