效果圖:
from PyQt5.QtCore import Qt, QRectF from PyQt5.QtGui import QColor, QPen, QBrush, QFont from PyQt5.QtWidgets import (QGraphicsView, QGraphicsScene, QApplication) class MainWindow(QGraphicsView): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # 創建場景 self.scene = MyGraphScene(self) # 在場景中添加文字 self.addPoint(0, 0, "p1") self.addPoint(50, 100, "p2") self.addPoint(100, 0, "p3") self.setSceneRect(QRectF(-150, -150, 400, 400)) self.scale(2, 2) # 將場景加載到窗口 self.setScene(self.scene) def addPoint(self, x, y, name): self.scene.addEllipse(x, y, 16, 16, QPen(QColor(Qt.red)), QBrush(QColor(Qt.red))) text = self.scene.addText(name) text.setDefaultTextColor(QColor(Qt.red)) text.setFont(QFont("Courier New", 16)) text.setPos(x, y - 30) class MyGraphScene(QGraphicsScene): def __init__(self, parent=None): super(MyGraphScene, self).__init__(parent) def drawBackground(self, painter, rect): # 在這里可以繪制底板,比如網格 pass if __name__ == '__main__': import sys # 每個PyQt程序必須創建一個application對象,sys.argv 參數是命令行中的一組參數 # 注意:application在 PyQt5.QtWidgets 模塊中 # 注意:application在 PyQt4.QtGui 模塊中 app = QApplication(sys.argv) # 創建桌面窗口 mainWindow = MainWindow() # 顯示桌面窗口 mainWindow.show() sys.exit(app.exec_())
使用概要:
1、創建繼承自QGraphicsView的窗口
2、創建繼承自QGraphicsScene的畫布
3、將畫布設置給View窗口QGraphicsView::setScene(self.scene)
4、自由的在畫布上添加元素:
①通過已經封裝好的方法,如前面代碼使用的
②自定義item,繼承自QGraphicsItem該類,并通過QGraphicsScene::addItem(item)的方法將item添加到畫布
QGraphicsView的API
QGraphicsScene的API
PS.這一篇是為下一篇做一個鋪墊,下一篇將做一個預覽窗口,是以QGraphicsScene、QGraphicsView 這兩個類為基礎實現的
傳送鏈接:PyQt制作預覽窗口游戲中的小地圖
以上就是pyqt5教程QGraphicsScene及QGraphicsView使用基礎的詳細內容,更多關于pyqt5使用基礎的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/weixin_40301728/article/details/109629671