【说明】

好吧,坦白从宽,我是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 基础绘画例子的更多相关文章

  1. [Qt扒手2] PyQt5 路径绘画例子

    [说明] 此例扒自 Qt 官网,原例是 C++ 代码,我把它改写成了 Python + PyQt5 版本. 有了前一个例子的成功,这个例子改写的非常之快.记得第一个例子花了我几天的时间,而这个例子只花 ...

  2. PyQt5基础应用一

    一.PyQt5基础   1.1 创建窗口 import sys from PyQt5.QtWidgets import QApplication, QWidget if __name__ == '__ ...

  3. PyQt5基础控件

    QLabel标签 功能:在界面上显示文字.图片.链接等 接口: 方法 描述 setText() 设置显示的内容 setAlignment() 设置文字对齐方式 setToolTip() 设置提示信息 ...

  4. Qt入门之基础篇 ( 二 ) :Qt项目建立、编译、运行和发布过程解析

    转载请注明出处:CN_Simo. 题解: 本篇内容主讲Qt应用从创建到发布的整个过程,旨在帮助读者能够快速走进Qt的世界. 本来计划是讲解Qt源码静态编译,如此的话读者可能并不能清楚地知道为何要静态编 ...

  5. Qt入门之基础篇(三):掌握Qt4的静态编译基本方法

    转载载请注明出处:CN_Simo. 导语: 前两章都提到过“静态编译”(Static Compilation),在Windows下一次静态编译差不多需要长达三个小时才能完成,而且还非常容易由于各种原因 ...

  6. Qt入门之基础篇 ( 一 ) :Qt4及Qt5的下载与安装

    转载请注明出处:CN_Simo. 导语: Qt是一个跨平台的C++图形界面应用程序框架.它提供给开发者建立图形用户界面所需的功能,广泛用于开发GUI程序,也可用于开发非GUI程序.Qt很容易扩展,并且 ...

  7. 【转】 Pro Android学习笔记(九七):BroadcastReceiver(1):基础小例子

    目录(?)[-] 基础小例子 发送Broadcast intent 运行情况 应用间的广播 文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog ...

  8. 【转】 Pro Android学习笔记(三九):Fragment(4):基础小例子-续

    目录(?)[-] Step 3实现简介显示类DetailFragment 创建实例 编写所需的生命周期代码 Step 4实现showDetailint index如何管理fragment fragme ...

  9. 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 ...

随机推荐

  1. Oracle EBS AR 更新客户组织层

    declare -- Local variables here i integer; g_module ) := 'TCA_V2_API'; lrec_org hz_party_v2pub.organ ...

  2. Vue2学习笔记:实例

    1.实例 <!DOCTYPE html> <html> <head> <title></title> <script src=&quo ...

  3. [翻译] ValueTrackingSlider

    ValueTrackingSlider What is it? A UISlider Subclass that displays live values in a popUpView. It’s i ...

  4. 多线程应用-函数方式(thread)

    多线程只能使用一颗CPU,无法发挥多核心的优势.计算密集型用python的多线程效果不明显的,I/O密集型才能看出效果,可以发挥多核优势. GIL是全局资源锁,所以,如果没有涉及到资源的调用,是不会体 ...

  5. php面试宝典

    1.表单中 get与post提交方法的区别? 答:get是发送请求HTTP协议通过url参数传递进行接收,而post是实体数据,可以通过表单提交大量信息. 2.session与cookie的区别? 答 ...

  6. RYU基础整理

    1. RYU结构,源码 1.1 RYU文件目录 下面介绍ryu/ryu目录下的主要目录内容. base base中有一个非常重要的文件:app_manager.py,其作用是RYU应用的管理中心.用于 ...

  7. Jenkins 配合 GitLab 实现分支的自动合并、自动创建 Tag

    Jenkins 配合 GitLab 实现分支的自动合并.自动创建 Tag 背景 GitFlow工作流简介 Gitflow工作流定义了一个围绕项目发布的严格分支模型,它会相对复杂一点,但提供了用于一个健 ...

  8. 【原创】python requests 库底层Sockets处于close_wait状态

    以前对于Requests库只是简单是使用,在现在公司的后台中,有多个接口是直接使用requests.get .post之类的方法来做的,进行过一段时间的压力测试,发现性能低的可怜,且linux服务器有 ...

  9. 利用Intellij IDEA开发Spark程序

    网上例子大多是基于scala的,并且配置基于sbt.scala的eclipse环境超级麻烦,所以下载IDEA. 准备:jdk,IDEA安装(可以不用事先安装sbt和Scala,这在IDEA里都可以pl ...

  10. 深入 Java 调试体系: 第 1 部分,初探JPDA 体系

    JPDA(Java Platform Debugger Architecture)是 Java 平台调试体系结构的缩写,通过 JPDA 提供的 API,开发人员可以方便灵活的搭建 Java 调试应用程 ...