![[Qt扒手] PyQt5 基础绘画例子 [Qt扒手] PyQt5 基础绘画例子](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
【说明】
好吧,坦白从宽,我是Qt扒手(不要鄙视我)。这是我根据qt官网提供的C++版本的例子(http://doc.qt.io/qt-5/qtwidgets-painting-basicdrawing-example.html),改编而成的Python版本。
由于本人没有C++基础,其难度之大,自不待言。
不过,还是*说的好:道路是艰难的,结果是光明的:)
本文基于 win7 + Python3.4 + PyQt5 环境
【效果图】
对比原C++的界面:
【源代码】
# File: Basic Draw Example.py
# Author: Robin
# Date: 2015.2.9
# C++: http://doc.qt.io/qt-5/qtwidgets-painting-basicdrawing-example.html from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import * class RenderArea(QWidget):
Shape = range(13)
(Line, Points, Polyline, Polygon, Rect, RoundedRect,
Ellipse, Arc, Chord, Pie, Path, Text, Pixmap) = Shape def __init__(self, parent=None):
super(RenderArea, self).__init__(parent) self.shape = self.Polygon
self.pen = Qt.NoPen
self.brush = Qt.NoBrush
self.antialiased = False
self.transformed = False
self.pixmap = QPixmap()
self.pixmap.load("images/qt-logo.png") self.setBackgroundRole(QPalette.Base)
self.setAutoFillBackground(True) def setShape(self, shape):
self.shape = shape
self.update() def setPen(self, pen):
self.pen = pen
self.update() def setBrush(self, brush):
self.brush = brush
self.update() def setAntialiased(self, antialiased):
self.antialiased = antialiased
self.update() def setTransformed(self, transformed):
self.transformed = transformed
self.update() def paintEvent(self, event):
points = [QPoint(10, 80), QPoint(20, 10), QPoint(80, 30), QPoint(90, 70)]
rect = QRect(10, 20, 80, 60)
path = QPainterPath()
path.moveTo(20, 80)
path.lineTo(20, 30)
path.cubicTo(80, 0, 50, 50, 80, 80)
startAngle = 20 * 16
arcLength = 120 * 16 painter = QPainter()
painter.begin(self)
painter.setPen(self.pen)
painter.setBrush(self.brush) if self.antialiased:
painter.setRenderHint(QPainter.Antialiasing, True)
for x in range(0, self.width(), 100):
for y in range(0, self.height(), 100):
painter.save() # 在画笔改变之前保存初始设置,即原点(0,0)处的设置
painter.translate(x, y)
if self.transformed:
painter.translate(50, 50)
painter.rotate(60.0)
painter.scale(0.6, 0.9)
painter.translate(-50, -50)
if self.shape == self.Line:
painter.drawLine(rect.bottomLeft(), rect.topRight())
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), Qt.WindingFill)
elif self.shape == self.Rect:
painter.drawRect(rect)
elif self.shape == self.RoundedRect:
painter.drawRoundedRect(rect, 25, 25, Qt.RelativeSize)
elif self.shape == self.Ellipse:
painter.drawEllipse(rect)
elif self.shape == self.Arc:
painter.drawArc(rect, startAngle, arcLength)
elif self.shape == self.Chord:
painter.drawChord(rect, startAngle, arcLength)
elif self.shape == self.Pie:
painter.drawPie(rect, startAngle, arcLength)
elif self.shape == self.Path:
painter.drawPath(path)
elif self.shape == self.Text:
painter.drawText(rect, Qt.AlignCenter, "Qt by\nDigia")
elif self.shape == self.Pixmap:
painter.drawPixmap(10, 10, self.pixmap)
painter.restore() # 画完一个之后,将画笔还原到初始设置,即原点(0,0)处的设置。好处是便于计算下一次的坐标变换 painter.setPen(self.palette().dark().color())
painter.setBrush(Qt.NoBrush)
painter.setRenderHint(QPainter.Antialiasing, False)
painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
painter.end() def sizeHint(self):
return QSize(400, 200) def minimumSizeHint(self):
return QSize(100, 100) class MyWindow(QWidget): def __init__(self):
super(MyWindow, self).__init__()
self.setUi() self.shapeChanged()
self.penChanged()
self.brushChanged()
self.checkBox_antialiasing.setChecked(True) def setUi(self):
self.setWindowTitle("基础绘画例子")
self.resize(400,300)
self.renderArea = RenderArea() self.label_shape = QLabel("Shape:")
self.label_penStyle = QLabel("Pen Style:")
self.label_brushStyle = QLabel("Brush Style:")
self.label_penWidth = QLabel("Pen Width:")
self.label_penCap = QLabel("Pen Cap:")
self.label_penJoin = QLabel("Pen Join:") self.comboBox_shape = QComboBox()
self.comboBox_penStyle = QComboBox()
self.comboBox_brushStyle = QComboBox()
self.spinBox_penWidth = QSpinBox()
self.comboBox_penCap = QComboBox()
self.comboBox_penJoin = QComboBox() self.checkBox_antialiasing = QCheckBox("Antialiasing")
self.checkBox_transformations = QCheckBox("Transformations") gridLayout = QGridLayout() gridLayout.setColumnStretch(0, 1)
gridLayout.setColumnStretch(1, 4)
gridLayout.setColumnStretch(2, 1)
gridLayout.setColumnStretch(3, 1)
gridLayout.setColumnStretch(4, 4) gridLayout.setColumnMinimumWidth(2, 15)
gridLayout.setSpacing(15)
#gridLayout.setMargin(10) gridLayout.addWidget(self.renderArea, 0, 0, 1, 5)
gridLayout.addWidget(self.label_shape, 1, 0)
gridLayout.addWidget(self.label_penStyle, 2, 0)
gridLayout.addWidget(self.label_brushStyle, 3, 0)
gridLayout.addWidget(self.checkBox_antialiasing, 4, 0, 1, 2)
gridLayout.addWidget(self.comboBox_shape, 1, 1)
gridLayout.addWidget(self.comboBox_penStyle, 2, 1)
gridLayout.addWidget(self.comboBox_brushStyle, 3, 1)
gridLayout.addWidget(self.label_penWidth, 1, 3)
gridLayout.addWidget(self.label_penCap, 2, 3)
gridLayout.addWidget(self.label_penJoin, 3, 3)
gridLayout.addWidget(self.checkBox_transformations, 4, 3, 1, 2)
gridLayout.addWidget(self.spinBox_penWidth, 1, 4)
gridLayout.addWidget(self.comboBox_penCap, 2, 4)
gridLayout.addWidget(self.comboBox_penJoin, 3, 4) self.setLayout(gridLayout) #self.checkBox_antialiasing.setChecked(True)
#Line, Points, Polyline, Polygon, Rect, RoundedRect,
#Ellipse, Arc, Chord, Pie, Path, Text, Pixmap
self.comboBox_shape.addItem('Line')
self.comboBox_shape.addItem('Points')
self.comboBox_shape.addItem('Polyline')
self.comboBox_shape.addItem('Polygon')
self.comboBox_shape.addItem('Rect')
self.comboBox_shape.addItem('RoundedRect')
self.comboBox_shape.addItem('Ellipse')
self.comboBox_shape.addItem('Arc')
self.comboBox_shape.addItem('Chord')
self.comboBox_shape.addItem('Pie')
self.comboBox_shape.addItem('Path')
self.comboBox_shape.addItem('Text')
self.comboBox_shape.addItem('Pixmap') self.spinBox_penWidth.setRange(0, 20)
#self.spinBox_penWidth.setSpecialValue('0 (cosmetic pen)') self.comboBox_penStyle.addItem('Solid',Qt.SolidLine)
self.comboBox_penStyle.addItem('Dash',Qt.DashLine)
self.comboBox_penStyle.addItem('Dot',Qt.DotLine)
self.comboBox_penStyle.addItem('Dash Dot',Qt.DashDotLine)
self.comboBox_penStyle.addItem('Dash Dot Dot',Qt.DashDotDotLine)
self.comboBox_penStyle.addItem('None',Qt.NoPen) self.comboBox_penCap.addItem('Flat',Qt.FlatCap)
self.comboBox_penCap.addItem('Square',Qt.SquareCap)
self.comboBox_penCap.addItem('Round',Qt.RoundCap) self.comboBox_penJoin.addItem('Miter',Qt.MiterJoin)
self.comboBox_penJoin.addItem('Bebel',Qt.BevelJoin)
self.comboBox_penJoin.addItem('Round',Qt.RoundJoin) self.comboBox_brushStyle.addItem('Linear Gradient',Qt.LinearGradientPattern)
self.comboBox_brushStyle.addItem('Radial Gradient',Qt.RadialGradientPattern)
self.comboBox_brushStyle.addItem('Conical Gradient',Qt.ConicalGradientPattern)
self.comboBox_brushStyle.addItem('Texture',Qt.TexturePattern)
self.comboBox_brushStyle.addItem('Solid',Qt.SolidPattern)
self.comboBox_brushStyle.addItem('Horizontal',Qt.HorPattern)
self.comboBox_brushStyle.addItem('Vertical',Qt.VerPattern)
self.comboBox_brushStyle.addItem('Cross',Qt.CrossPattern)
self.comboBox_brushStyle.addItem('Backward Diagonal',Qt.BDiagPattern)
self.comboBox_brushStyle.addItem('Forward Diagonal',Qt.FDiagPattern)
self.comboBox_brushStyle.addItem('Diagonal Cross',Qt.DiagCrossPattern)
self.comboBox_brushStyle.addItem('Dense 1',Qt.Dense1Pattern)
self.comboBox_brushStyle.addItem('Dense 2',Qt.Dense2Pattern)
self.comboBox_brushStyle.addItem('Dense 3',Qt.Dense3Pattern)
self.comboBox_brushStyle.addItem('Dense 4',Qt.Dense4Pattern)
self.comboBox_brushStyle.addItem('Dense 5',Qt.Dense5Pattern)
self.comboBox_brushStyle.addItem('Dense 6',Qt.Dense6Pattern)
self.comboBox_brushStyle.addItem('Dense 7',Qt.Dense7Pattern)
self.comboBox_brushStyle.addItem('None',Qt.NoBrush) self.comboBox_shape.currentIndexChanged.connect(self.shapeChanged)
self.comboBox_brushStyle.currentIndexChanged.connect(self.brushChanged)
self.spinBox_penWidth.valueChanged.connect(self.penChanged)
self.comboBox_penStyle.currentIndexChanged.connect(self.penChanged)
self.comboBox_penCap.currentIndexChanged.connect(self.penChanged)
self.comboBox_penJoin.currentIndexChanged.connect(self.penChanged)
self.checkBox_antialiasing.clicked.connect(self.renderArea.setAntialiased)
self.checkBox_transformations.clicked.connect(self.renderArea.setTransformed) def shapeChanged(self):
index = self.comboBox_shape.currentIndex()
shape = self.renderArea.Shape[index]
self.renderArea.setShape(shape) def penChanged(self):
width = self.spinBox_penWidth.value()
style = Qt.PenStyle(self.comboBox_penStyle.itemData(self.comboBox_penStyle.currentIndex(),Qt.UserRole))
cap = Qt.PenCapStyle(self.comboBox_penCap.itemData(self.comboBox_penCap.currentIndex(),Qt.UserRole))
join = Qt.PenJoinStyle(self.comboBox_penJoin.itemData(self.comboBox_penJoin.currentIndex(),Qt.UserRole))
self.renderArea.setPen(QPen(Qt.blue, width, style, cap, join)) def brushChanged(self):
style = Qt.BrushStyle(self.comboBox_brushStyle.itemData(self.comboBox_brushStyle.currentIndex(),Qt.UserRole))
if style == Qt.LinearGradientPattern:
linearGradient = QLinearGradient(0, 0, 100, 100)
linearGradient.setColorAt(0.0, Qt.white)
linearGradient.setColorAt(0.2, Qt.green)
linearGradient.setColorAt(1.0, Qt.black)
self.renderArea.setBrush(linearGradient)
elif style == Qt.RadialGradientPattern:
radialGradient = QRadialGradient(50, 50, 50, 70, 70);
radialGradient.setColorAt(0.0, Qt.white)
radialGradient.setColorAt(0.2, Qt.green)
radialGradient.setColorAt(1.0, Qt.black)
self.renderArea.setBrush(radialGradient)
elif style == Qt.ConicalGradientPattern:
conicalGradient = QConicalGradient(50, 50, 150)
conicalGradient.setColorAt(0.0, Qt.white)
conicalGradient.setColorAt(0.2, Qt.green)
conicalGradient.setColorAt(1.0, Qt.black)
self.renderArea.setBrush(conicalGradient)
elif style == Qt.TexturePattern:
self.renderArea.setBrush(QBrush(QPixmap("images/brick.png")))
else:
self.renderArea.setBrush(QBrush(Qt.green, style)) if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())