In this Python PySide6 lesson we are going to learn about Python PySide6 QGraphicsView & QGraphicsScene.
Introduction to QGraphicsView & QGraphicsScene
QGraphicsView and QGraphicsScene are classes in the PySide6 library used to create interactive graphics based user interfaces. QGraphicsView is widget that displays the contents of QGraphicsScene. QGraphicsScene is container for QGraphicsItems which can be added to the scene and displayed in the QGraphicsView.
The QGraphicsView widget provides several useful features for handling interactive graphics, including panning and zooming, mouse interaction, and key presses. The QGraphicsScene provides a 2D drawing surface where items can be added and manipulated.
This is an example of using QGraphicsView and QGraphicsScene to display a rectangle and a text item:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
from PySide6.QtWidgets import QGraphicsView, QGraphicsScene, QGraphicsRectItem, QGraphicsTextItem from PySide6.QtCore import Qt from PySide6.QtWidgets import QApplication class MyGraphicsView(QGraphicsView): def __init__(self): super().__init__() #set the window title self.setWindowTitle("GeeksCoders.com") # Create scene self.scene = QGraphicsScene(self) self.setScene(self.scene) # Add a rectangle item to the scene rect_item = QGraphicsRectItem(0, 0, 200, 50) rect_item.setBrush(Qt.red) self.scene.addItem(rect_item) # Add a text item to the scene text_item = QGraphicsTextItem("GeeksCoders.com") text_item.setPos(10, 10) self.scene.addItem(text_item) if __name__ == "__main__": import sys app = QApplication(sys.argv) view = MyGraphicsView() view.show() sys.exit(app.exec()) |
In this example we have created subclass of QGraphicsView called MyGraphicsView. In the __init__ method we have created QGraphicsScene and set it as the scene for the view using the setScene method. after that we add QGraphicsRectItem and QGraphicsTextItem to the scene using the addItem method.
The QGraphicsRectItem is created with a rectangle of size 200×50 and a red brush. The QGraphicsTextItem is initialized with the text “GeeksCoders.com” and positioned at (10, 10) using the setPos method.
Finally, we create an instance of MyGraphicsView and show it. When the application is run, a window containing the rectangle and text items will be displayed.
Run the complete code and this will be the result.