PyQt5利用QPainter繪制各種圖形的實(shí)例
這個(gè)例子我做了好幾天:
1)官網(wǎng)C++的源碼,改寫(xiě)成PyQt5版本的代碼,好多細(xì)節(jié)不會(huì)轉(zhuǎn)化
2)網(wǎng)上的PyQt的例子根本運(yùn)行不了
填了無(wú)數(shù)個(gè)坑,結(jié)合二者,終于能完成了一個(gè)關(guān)于繪圖的東西。這個(gè)過(guò)程也掌握了很多新的知識(shí)點(diǎn)
【知識(shí)點(diǎn)】
1、關(guān)于多個(gè)點(diǎn)的使用
poitns = [QPoint(10, 80), QPoint(20, 10), QPoint(80, 30), QPoint(90, 70)]
請(qǐng)看:
# 定義多個(gè)點(diǎn) points = [QPoint(10, 80), QPoint(20, 10), QPoint(80, 30), QPoint(90, 70)] # ===直接使用 points 會(huì)報(bào)錯(cuò)!========= # ... elif self.shape == self.Points: painter.drawPoints(points) elif self.shape == self.Polyline: painter.drawPolyline(points) elif self.shape == self.Polygon: painter.drawPolygon(points, 4) # ... # ===把 points 用 QPolygon()包裹起來(lái)才正確!========= # ... elif self.shape == self.Points: painter.drawPoints(QPolygon(points)) elif self.shape == self.Polyline: painter.drawPolyline(QPolygon(points)) elif self.shape == self.Polygon: painter.drawPolygon(QPolygon(points), 4) # ...
2、在QDialog窗體中顯示QWidget部件
【效果圖】
【資源】
//img.jbzj.com/file_images/article/201710/brick.png
//img.jbzj.com/file_images/article/201710/qt-logo.png
【代碼】
import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class StockDialog(QWidget): def __init__(self, parent=None): super(StockDialog, self).__init__(parent) self.setWindowTitle("利用QPainter繪制各種圖形") mainSplitter = QSplitter(Qt.Horizontal) mainSplitter.setOpaqueResize(True) frame = QFrame(mainSplitter) mainLayout = QGridLayout(frame) #mainLayout.setMargin(10) mainLayout.setSpacing(6) label1=QLabel("形狀:") label2=QLabel("畫(huà)筆線寬:") label3=QLabel("畫(huà)筆顏色:") label4=QLabel("畫(huà)筆風(fēng)格:") label5=QLabel("畫(huà)筆頂端:") label6=QLabel("畫(huà)筆連接點(diǎn):") label7=QLabel("畫(huà)刷風(fēng)格:") label8=QLabel("畫(huà)刷顏色:") self.shapeComboBox = QComboBox() self.shapeComboBox.addItem("Line", "Line") self.shapeComboBox.addItem("Rectangle", "Rectangle") self.shapeComboBox.addItem('Rounded Rectangle','Rounded Rectangle') self.shapeComboBox.addItem('Ellipse','Ellipse') self.shapeComboBox.addItem('Pie','Pie') self.shapeComboBox.addItem('Chord','Chord') self.shapeComboBox.addItem('Path','Path') self.shapeComboBox.addItem('Polygon','Polygon') self.shapeComboBox.addItem('Polyline','Polyline') self.shapeComboBox.addItem('Arc','Arc') self.shapeComboBox.addItem('Points','Points') self.shapeComboBox.addItem('Text','Text') self.shapeComboBox.addItem('Pixmap','Pixmap') self.widthSpinBox = QSpinBox() self.widthSpinBox.setRange(0,20) self.penColorFrame = QFrame() self.penColorFrame.setAutoFillBackground(True) self.penColorFrame.setPalette(QPalette(Qt.blue)) self.penColorPushButton = QPushButton("更改") self.penStyleComboBox = QComboBox() self.penStyleComboBox.addItem("Solid",Qt.SolidLine) self.penStyleComboBox.addItem('Dash', Qt.DashLine) self.penStyleComboBox.addItem('Dot', Qt.DotLine) self.penStyleComboBox.addItem('Dash Dot', Qt.DashDotLine) self.penStyleComboBox.addItem('Dash Dot Dot', Qt.DashDotDotLine) self.penStyleComboBox.addItem('None', Qt.NoPen) self.penCapComboBox = QComboBox() self.penCapComboBox.addItem("Flat",Qt.FlatCap) self.penCapComboBox.addItem('Square', Qt.SquareCap) self.penCapComboBox.addItem('Round', Qt.RoundCap) self.penJoinComboBox = QComboBox() self.penJoinComboBox.addItem("Miter",Qt.MiterJoin) self.penJoinComboBox.addItem('Bebel', Qt.BevelJoin) self.penJoinComboBox.addItem('Round', Qt.RoundJoin) self.brushStyleComboBox = QComboBox() self.brushStyleComboBox.addItem("Linear Gradient",Qt.LinearGradientPattern) self.brushStyleComboBox.addItem('Radial Gradient', Qt.RadialGradientPattern) self.brushStyleComboBox.addItem('Conical Gradient', Qt.ConicalGradientPattern) self.brushStyleComboBox.addItem('Texture', Qt.TexturePattern) self.brushStyleComboBox.addItem('Solid', Qt.SolidPattern) self.brushStyleComboBox.addItem('Horizontal', Qt.HorPattern) self.brushStyleComboBox.addItem('Vertical', Qt.VerPattern) self.brushStyleComboBox.addItem('Cross', Qt.CrossPattern) self.brushStyleComboBox.addItem('Backward Diagonal', Qt.BDiagPattern) self.brushStyleComboBox.addItem('Forward Diagonal', Qt.FDiagPattern) self.brushStyleComboBox.addItem('Diagonal Cross', Qt.DiagCrossPattern) self.brushStyleComboBox.addItem('Dense 1', Qt.Dense1Pattern) self.brushStyleComboBox.addItem('Dense 2', Qt.Dense2Pattern) self.brushStyleComboBox.addItem('Dense 3', Qt.Dense3Pattern) self.brushStyleComboBox.addItem('Dense 4', Qt.Dense4Pattern) self.brushStyleComboBox.addItem('Dense 5', Qt.Dense5Pattern) self.brushStyleComboBox.addItem('Dense 6', Qt.Dense6Pattern) self.brushStyleComboBox.addItem('Dense 7', Qt.Dense7Pattern) self.brushStyleComboBox.addItem('None', Qt.NoBrush) self.brushColorFrame = QFrame() self.brushColorFrame.setAutoFillBackground(True) self.brushColorFrame.setPalette(QPalette(Qt.green)) self.brushColorPushButton = QPushButton("更改") labelCol=0 contentCol=1 #建立布局 mainLayout.addWidget(label1,1,labelCol) mainLayout.addWidget(self.shapeComboBox,1,contentCol) mainLayout.addWidget(label2,2,labelCol) mainLayout.addWidget(self.widthSpinBox,2,contentCol) mainLayout.addWidget(label3,4,labelCol) mainLayout.addWidget(self.penColorFrame,4,contentCol) mainLayout.addWidget(self.penColorPushButton,4,3) mainLayout.addWidget(label4,6,labelCol) mainLayout.addWidget(self.penStyleComboBox,6,contentCol) mainLayout.addWidget(label5,8,labelCol) mainLayout.addWidget(self.penCapComboBox,8,contentCol) mainLayout.addWidget(label6,10,labelCol) mainLayout.addWidget(self.penJoinComboBox,10,contentCol) mainLayout.addWidget(label7,12,labelCol) mainLayout.addWidget(self.brushStyleComboBox,12,contentCol) mainLayout.addWidget(label8,14,labelCol) mainLayout.addWidget(self.brushColorFrame,14,contentCol) mainLayout.addWidget(self.brushColorPushButton,14,3) mainSplitter1 = QSplitter(Qt.Horizontal) mainSplitter1.setOpaqueResize(True) stack1 = QStackedWidget() stack1.setFrameStyle(QFrame.Panel|QFrame.Raised) self.area = PaintArea() stack1.addWidget(self.area) frame1 = QFrame(mainSplitter1) mainLayout1 = QVBoxLayout(frame1) #mainLayout1.setMargin(10) mainLayout1.setSpacing(6) mainLayout1.addWidget(stack1) layout = QGridLayout(self) layout.addWidget(mainSplitter1,0,0) layout.addWidget(mainSplitter,0,1) self.setLayout(layout) #信號(hào)和槽函數(shù) self.shapeComboBox.activated.connect(self.slotShape) self.widthSpinBox.valueChanged.connect(self.slotPenWidth) self.penColorPushButton.clicked.connect(self.slotPenColor) self.penStyleComboBox.activated.connect(self.slotPenStyle) self.penCapComboBox.activated.connect(self.slotPenCap) self.penJoinComboBox.activated.connect(self.slotPenJoin) self.brushStyleComboBox.activated.connect(self.slotBrush) self.brushColorPushButton.clicked.connect(self.slotBrushColor) self.slotShape(self.shapeComboBox.currentIndex()) self.slotPenWidth(self.widthSpinBox.value()) self.slotBrush(self.brushStyleComboBox.currentIndex()) def slotShape(self,value): shape = self.area.Shape[value] self.area.setShape(shape) def slotPenWidth(self,value): color = self.penColorFrame.palette().color(QPalette.Window) style = Qt.PenStyle(self.penStyleComboBox.itemData(self.penStyleComboBox.currentIndex(),Qt.UserRole)) cap = Qt.PenCapStyle(self.penCapComboBox.itemData(self.penCapComboBox.currentIndex(),Qt.UserRole)) join = Qt.PenJoinStyle(self.penJoinComboBox.itemData(self.penJoinComboBox.currentIndex(),Qt.UserRole)) self.area.setPen(QPen(color,value,style,cap,join)) def slotPenStyle(self,value): self.slotPenWidth(value) def slotPenCap(self,value): self.slotPenWidth(value) def slotPenJoin(self,value): self.slotPenWidth(value) def slotPenColor(self): color = QColorDialog.getColor(Qt.blue) self.penColorFrame.setPalette(QPalette(color)) self.area.setPen(QPen(color)) def slotBrushColor(self): color = QColorDialog.getColor(Qt.blue) self.brushColorFrame.setPalette(QPalette(color)) self.slotBrush(self.brushStyleComboBox.currentIndex()) def slotBrush(self,value): color = self.brushColorFrame.palette().color(QPalette.Window) style = Qt.BrushStyle(self.brushStyleComboBox.itemData(value,Qt.UserRole)) if(style == Qt.LinearGradientPattern): linearGradient = QLinearGradient(0,0,400,400) linearGradient.setColorAt(0.0,Qt.white) linearGradient.setColorAt(0.2,color) linearGradient.setColorAt(1.0,Qt.black) self.area.setBrush(linearGradient) elif style ==Qt.RadialGradientPattern: radialGradient = QRadialGradient(200, 200, 80, 70, 70); radialGradient.setColorAt(0.0, Qt.white) radialGradient.setColorAt(0.2, Qt.green) radialGradient.setColorAt(1.0, Qt.black) self.area.setBrush(radialGradient) elif(style == Qt.ConicalGradientPattern): conicalGradient = QConicalGradient(200,200,30) conicalGradient.setColorAt(0.0,Qt.white) conicalGradient.setColorAt(0.2,color) conicalGradient.setColorAt(1.0,Qt.black) self.area.setBrush(conicalGradient) elif(style == Qt.TexturePattern): self.area.setBrush(QBrush(QPixmap("images/brick.png"))) else: self.area.setBrush(QBrush(color,style)) class PaintArea(QWidget): def __init__(self): super(PaintArea,self).__init__() self.Shape = ["Line","Rectangle", 'Rounded Rectangle', "Ellipse", "Pie", 'Chord', "Path","Polygon", "Polyline", "Arc", "Points", "Text", "Pixmap"] self.setPalette(QPalette(Qt.white)) self.setAutoFillBackground(True) self.setMinimumSize(400,400) self.pen = QPen() self.brush = QBrush() def setShape(self,s): self.shape = s self.update() def setPen(self,p): self.pen = p self.update() def setBrush(self,b): self.brush = b self.update() def paintEvent(self,QPaintEvent): p = QPainter(self) p.setPen(self.pen) p.setBrush(self.brush) rect = QRect(50,100,300,200) points = [QPoint(150,100),QPoint(300,150),QPoint(350,250),QPoint(100,300)] startAngle = 30 * 16 spanAngle = 120 * 16 path = QPainterPath(); path.addRect(150,150,100,100) path.moveTo(100,100) path.cubicTo(300,100,200,200,300,300) path.cubicTo(100,300,200,200,100,100) if self.shape == "Line": p.drawLine(rect.topLeft(),rect.bottomRight()) elif self.shape == "Rectangle": p.drawRect(rect) elif self.shape == 'Rounded Rectangle': p.drawRoundedRect(rect, 25, 25, Qt.RelativeSize) elif self.shape == "Ellipse": p.drawEllipse(rect) elif self.shape == "Polygon": p.drawPolygon(QPolygon(points),Qt.WindingFill) elif self.shape == "Polyline": p.drawPolyline(QPolygon(points)) elif self.shape == "Points": p.drawPoints(QPolygon(points)) elif self.shape == "Pie": p.drawPie(rect, startAngle, spanAngle) elif self.shape == "Arc": p.drawArc(rect,startAngle,spanAngle) elif self.shape == "Chord": p.drawChord(rect, startAngle, spanAngle) elif self.shape == "Path": p.drawPath(path) elif self.shape == "Text": p.drawText(rect,Qt.AlignCenter,"Hello Qt!") elif self.shape == "Pixmap": p.drawPixmap(150,150,QPixmap("images/qt-logo.png")) if __name__=='__main__': app = QApplication(sys.argv) form = StockDialog() form.show() app.exec_()
以上這篇PyQt5利用QPainter繪制各種圖形的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用python PIL庫(kù)批量對(duì)圖片添加水印的過(guò)程詳解
平常我們想給某些圖片添加文字水印,方法有很多,也有很多的工具可以方便的進(jìn)行,今天主要是對(duì)PIL庫(kù)的應(yīng)用,結(jié)合Python語(yǔ)言批量對(duì)圖片添加水印,文章通過(guò)代碼示例給大家介紹的非常詳細(xì),感興趣的同學(xué)可以參考一下2023-11-11Django將項(xiàng)目移動(dòng)到新環(huán)境的操作步驟
本文分步驟給大家介紹Django將項(xiàng)目移動(dòng)到新環(huán)境的方法,通過(guò)圖文示例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-08-08如何使用Python基于接口編程的方法實(shí)現(xiàn)
本文主要介紹了如何使用Python基于接口編程,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11python自定義函數(shù)def的應(yīng)用詳解
這篇文章主要介紹了python自定義函數(shù)def的應(yīng)用詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06pytorch查看網(wǎng)絡(luò)參數(shù)顯存占用量等操作
這篇文章主要介紹了pytorch查看網(wǎng)絡(luò)參數(shù)顯存占用量等操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-05-05Python 中對(duì) XML 文件的編碼轉(zhuǎn)換問(wèn)題
這篇文章主要介紹了Python 中對(duì) XML 文件的編碼轉(zhuǎn)換問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03Python讀取網(wǎng)頁(yè)內(nèi)容的方法
這篇文章主要介紹了Python讀取網(wǎng)頁(yè)內(nèi)容的方法,實(shí)例分析了Python基于URL讀取網(wǎng)頁(yè)內(nèi)容的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07Python xlrd讀取excel日期類(lèi)型的2種方法
這篇文章主要介紹了Python xlrd讀取excel日期類(lèi)型的2種方法,本文同時(shí)講解了xlrd讀取excel某個(gè)單元格的方法,需要的朋友可以參考下2015-04-04python斯皮爾曼spearman相關(guān)性分析實(shí)例
這篇文章主要為大家介紹了python斯皮爾曼spearman相關(guān)性分析實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02