In this lesson we want to learn about Python PySide6 Draw Rectangle, to draw rectangle using PySide6, you can use QPainter class, which provides different methods for drawing shapes and lines on QWidget or other paint device.
This is an example code snippet that demonstrates how to draw rectangle using PySide6:
from PySide6.QtCore import Qt
from PySide6.QtGui import QColor, QPainter, QPen
from PySide6.QtWidgets import QApplication, QWidget
self.setWindowTitle('Draw Rectangle - GeeksCoders.com')
self.setGeometry(300, 300, 350, 250)
def paintEvent(self, event):
painter = QPainter(self)
painter.setPen(QPen(QColor('red'), 3, Qt.SolidLine))
painter.drawRect(50, 50, 200, 100)
if __name__ == '__main__':
app = QApplication()
ex = Example()
In this example we have created custom widget by subclassing QWidget. we override paintEvent method to handle the widget’s painting and use the QPainter object to draw rectangle.
First of all we have created QPainter object with the widget as its paint device. after that we set the pen properties to define the color, width and style of the rectangle’s border using the QPen class. and finally we use the drawRect method of the QPainter object to draw the rectangle with the specified position (x,y) and size (width, height).
You can use this code as a starting point to draw other shapes as well, such as circles or lines.
Run the complete code and this will be the result.
In summary QPainter is powerful class in PySide6 that allows you to perform custom drawing on widgets and other paint devices. by creating QPainter object, you can use its different methods to draw lines, rectangles, ellipses, polygons, text and images.