[Qt扒手] PyQt5 基础绘画例子
【说明】
好吧,坦白从宽,我是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_())
[Qt扒手] PyQt5 基础绘画例子的更多相关文章
- [Qt扒手2] PyQt5 路径绘画例子
[说明] 此例扒自 Qt 官网,原例是 C++ 代码,我把它改写成了 Python + PyQt5 版本. 有了前一个例子的成功,这个例子改写的非常之快.记得第一个例子花了我几天的时间,而这个例子只花 ...
- PyQt5基础应用一
一.PyQt5基础 1.1 创建窗口 import sys from PyQt5.QtWidgets import QApplication, QWidget if __name__ == '__ ...
- PyQt5基础控件
QLabel标签 功能:在界面上显示文字.图片.链接等 接口: 方法 描述 setText() 设置显示的内容 setAlignment() 设置文字对齐方式 setToolTip() 设置提示信息 ...
- Qt入门之基础篇 ( 二 ) :Qt项目建立、编译、运行和发布过程解析
转载请注明出处:CN_Simo. 题解: 本篇内容主讲Qt应用从创建到发布的整个过程,旨在帮助读者能够快速走进Qt的世界. 本来计划是讲解Qt源码静态编译,如此的话读者可能并不能清楚地知道为何要静态编 ...
- Qt入门之基础篇(三):掌握Qt4的静态编译基本方法
转载载请注明出处:CN_Simo. 导语: 前两章都提到过“静态编译”(Static Compilation),在Windows下一次静态编译差不多需要长达三个小时才能完成,而且还非常容易由于各种原因 ...
- Qt入门之基础篇 ( 一 ) :Qt4及Qt5的下载与安装
转载请注明出处:CN_Simo. 导语: Qt是一个跨平台的C++图形界面应用程序框架.它提供给开发者建立图形用户界面所需的功能,广泛用于开发GUI程序,也可用于开发非GUI程序.Qt很容易扩展,并且 ...
- 【转】 Pro Android学习笔记(九七):BroadcastReceiver(1):基础小例子
目录(?)[-] 基础小例子 发送Broadcast intent 运行情况 应用间的广播 文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog ...
- 【转】 Pro Android学习笔记(三九):Fragment(4):基础小例子-续
目录(?)[-] Step 3实现简介显示类DetailFragment 创建实例 编写所需的生命周期代码 Step 4实现showDetailint index如何管理fragment fragme ...
- PyQt5 基础知识(六):展示控件
目录 3. 展示控件 3.1 QLabel 3.1.1 描述 3.1.2 功能作用 3.1.2.1 基本功能 3.1.2.2 文本交互 3.1.2.3 内容操作 3.1.2.3.1 文本字符串 3.1 ...
随机推荐
- WinForm 应用程序禁止多个进程运行
方法一: 禁止多个进程运行 using System; using System.Collections.Generic; using System.Linq; using System.Window ...
- windows下npm安装vue
一.使用之前,我们先来掌握3个东西是用来干什么的. npm: Nodejs下的包管理器. webpack: 它主要的用途是通过CommonJS的语法把所有浏览器端需要发布的静态资源做相应的准备,比如资 ...
- idea插件 总结 自认用比较不错的插件的总结
1.Background Image Plus 设置你喜欢的图片,提升你编码逼格!还可以设置以轮播图的形式变换图片 还可以设置图片的透明度等现实的方式 2.CodeGlance 类似SublimeTe ...
- 【教程】【FLEX】#004 反射机制
总结: 目前用到反射的主要有两个方法 1. getDefinitionByName //根据类名,返回对象(反射实例化对象) 2. describeType ...
- UE4的csv文件导入、URL地址的读取及动态材质的设置
1.csv文件的导入 UE4是可以直接导入csv文件的,其过程和其他文件资源(图片Texture,静态网格物体StaticMesh等)相似,但在导入过程中有一些需要注意的点. 如下图所示 这是一份编辑 ...
- 【ansible】Windows开启远程控制错误解决方案:无法检查防火墙状态
这个在老版本的Windows系统才有这种bug.例如Windows 2008 R2和Windows 7,如果你的系统的阿里云的Windows server 2008 R2,无需装这个,好像阿里云的系统 ...
- 【原创】Python 对象创建过程中元类, __new__, __call__, __init__ 的处理
原始type: type是最原始的元类,其__call__方法是在你使用" t_class = type(classname_string, base_classes_tuple, attr ...
- 2002. [HNOI2010]弹飞绵羊【LCT】
Description 某天,Lostmonkey发明了一种超级弹力装置,为了在他的绵羊朋友面前显摆,他邀请小绵羊一起玩个游戏.游戏一开始,Lostmonkey在地上沿着一条直线摆上n个装置,每个装置 ...
- 「GXOI / GZOI2019」旧词
题目 确定这不是思博题 看起来很神仙,本来以为是\([LNOI2014]LCA\)的加强版,结果发现一个点的贡献是\(s_i\times (deep_i^k-(deep_i-1)^k)\),\(s_i ...
- gcd?人生赢家!
题目背景 原创:b2019dy gcd是一个热爱游戏的人 题目描述 gcd最近在玩一个有趣的游戏 我们把这个游戏抽象成一张图,图上有n个点,我们需要寻找总计m件宝物,它们分布在图上,对于每件宝物而言, ...