pyqt5教程QGraphicsScene及QGraphicsView使用基礎(chǔ)
效果圖:
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) # 創(chuàng)建場景 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): # 在這里可以繪制底板,比如網(wǎng)格 pass if __name__ == '__main__': import sys # 每個(gè)PyQt程序必須創(chuàng)建一個(gè)application對象,sys.argv 參數(shù)是命令行中的一組參數(shù) # 注意:application在 PyQt5.QtWidgets 模塊中 # 注意:application在 PyQt4.QtGui 模塊中 app = QApplication(sys.argv) # 創(chuàng)建桌面窗口 mainWindow = MainWindow() # 顯示桌面窗口 mainWindow.show() sys.exit(app.exec_())
使用概要:
1、創(chuàng)建繼承自QGraphicsView的窗口
2、創(chuàng)建繼承自QGraphicsScene的畫布
3、將畫布設(shè)置給View窗口QGraphicsView::setScene(self.scene)
4、自由的在畫布上添加元素:
①通過已經(jīng)封裝好的方法,如前面代碼使用的
②自定義item,繼承自QGraphicsItem該類,并通過QGraphicsScene::addItem(item)的方法將item添加到畫布
QGraphicsView的API
QGraphicsScene的API
PS.這一篇是為下一篇做一個(gè)鋪墊,下一篇將做一個(gè)預(yù)覽窗口,是以QGraphicsScene、QGraphicsView 這兩個(gè)類為基礎(chǔ)實(shí)現(xiàn)的
傳送鏈接:PyQt制作預(yù)覽窗口游戲中的小地圖
以上就是pyqt5教程QGraphicsScene及QGraphicsView使用基礎(chǔ)的詳細(xì)內(nèi)容,更多關(guān)于pyqt5使用基礎(chǔ)的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。