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)建場(chǎng)景
self.scene = MyGraphScene(self)
# 在場(chǎng)景中添加文字
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)
# 將場(chǎng)景加載到窗口
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對(duì)象,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)的
以上就是pyqt5教程QGraphicsScene及QGraphicsView使用基礎(chǔ)的詳細(xì)內(nèi)容,更多關(guān)于pyqt5使用基礎(chǔ)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python 輸入一個(gè)數(shù)n,求n個(gè)數(shù)求乘或求和的實(shí)例
今天小編就為大家分享一篇python 輸入一個(gè)數(shù)n,求n個(gè)數(shù)求乘或求和的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-11-11
400多行Python代碼實(shí)現(xiàn)了一個(gè)FTP服務(wù)器
400多行Python代碼實(shí)現(xiàn)了一個(gè)FTP服務(wù)器,實(shí)現(xiàn)了比之前的xxftp更多更完善的功能2012-05-05
Python使用Tabulate庫(kù)實(shí)現(xiàn)格式化表格數(shù)據(jù)
在數(shù)據(jù)分析和軟件開發(fā)中,表格數(shù)據(jù)的展示是一個(gè)常見的需求,無論是簡(jiǎn)單的數(shù)據(jù)報(bào)告,還是復(fù)雜的數(shù)據(jù)可視化,表格都是一種直觀且有效的信息展示方式,tabulate庫(kù)是一個(gè)非常實(shí)用的工具,它可以幫助我們輕松地將數(shù)據(jù)格式化為各種表格形式,本文將詳細(xì)介紹tabulate庫(kù)的使用方法2025-02-02

