PyQt5利用QPainter绘制各种图形

这个例子我做了好几天:

1)官网C++的源码,改写成PyQt5版本的代码,好多细节不会转化

2)网上的PyQt的例子根本运行不了

填了无数个坑,结合二者,终于能完成了一个关于绘图的东西。这个过程也掌握了很多新的知识点

【知识点】

1、关于多个点的使用

poitns = [QPoint(10, 80), QPoint(20, 10), QPoint(80, 30), QPoint(90, 70)]

请看:

 1      # 定义多个点
 2      points = [QPoint(10, 80), QPoint(20, 10), QPoint(80, 30), QPoint(90, 70)]
 3
 4      # ===直接使用 points 会报错!=========
 5      # ...
 6      elif self.shape == self.Points:
 7            painter.drawPoints(points)
 8
 9      elif self.shape == self.Polyline:
10            painter.drawPolyline(points)
11
12      elif self.shape == self.Polygon:
13            painter.drawPolygon(points, 4)
14
15      # ...
16
17      # ===把 points 用 QPolygon()包裹起来才正确!=========
18      # ...
19      elif self.shape == self.Points:
20            painter.drawPoints(QPolygon(points))
21
22      elif self.shape == self.Polyline:
23            painter.drawPolyline(QPolygon(points))
24
25      elif self.shape == self.Polygon:
26            painter.drawPolygon(QPolygon(points), 4)
27
28      # ...

2、在QDialog窗体中显示QWidget部件

 

【效果图】

【资源】

http://doc.qt.io/qt-5/images/used-in-examples/painting/basicdrawing/images/brick.png

http://doc.qt.io/qt-5/images/used-in-examples/painting/basicdrawing/images/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("画笔线宽:")
        label3=QLabel("画笔颜色:")
        label4=QLabel("画笔风格:")
        label5=QLabel("画笔顶端:")
        label6=QLabel("画笔连接点:")
        label7=QLabel("画刷风格:")
        label8=QLabel("画刷颜色:")

        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)

        #信号和槽函数
        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_()

 

(罗兵 作于2015.02.05     01:58)

 

时间: 2024-10-25 01:17:07

PyQt5利用QPainter绘制各种图形的相关文章

Android编程开发之在Canvas中利用Path绘制基本图形(圆形,矩形,椭圆,三角形等)_Android

本文实例讲述了Android编程开发之在Canvas中利用Path绘制基本图形的方法.分享给大家供大家参考,具体如下: 在Android中绘制基本的集合图形,本程序就是自定义一个View组件,程序重写该View组件的onDraw(Canvase)方法,然后在该Canvas上绘制大量的基本的集合图形. 直接上代码: 1.自定义的View组件代码: package com.infy.configuration; import android.content.Context; import andro

在AutoCAD中快速绘制机械图形中心线

在机械工程制图中,中心线是最常见的一种图线,应用范围很广,使用十分频紧.AutoCAD虽然提供绘制直线段的命令,但没有直接提供绘制标准中心线的命令,用户如果要绘制标准中心线,需要事先根据国家制图标准设定标准中心线的线型和比例,并且在加载以后,用直线段绘制命令先绘制直线段,再使用图形编辑命令进行编辑修改才能得到所需要的中心线,此过程非常繁琐,而且还容易出错.事实上,AutoCAD具有开放性的体系结构和多重工业标准,允许用户采用高级程序设计语言对其进行扩充和修改,利用这一特点,本文介绍一种快速绘制机

巧用WPS文字绘图工具绘制标准图形

平时在用WPS编辑文档过程中,有时需要在文档中绘制(插入)图形,来配合文档对某一事件进行辅助说明,以达到深入浅出.通俗易懂的目的.但在实际操作过程中,有时看似简单的图形,可绘制起来却困难重重,因为在WPS绘图工具提供的自选图形中,并没有提供相应的图形供我们使用,而此时如果采用专业绘图软件,一来对专业知识要求高,操作复杂,二来也有点大材小用的感觉.其实,在WPS中如果对绘制的图形要求不是过于专业的话,只要我们多动脑筋,利用 WPS绘图工具中的自选图形,在加一些操作技巧可以绘制出来的. 一.基础技巧

[Qt教程] 第11篇 2D绘图(一)绘制简单图形

[Qt教程] 第11篇 2D绘图(一)绘制简单图形 楼主  发表于 2013-4-23 12:52:35 | 查看: 1398| 回复: 5 绘制简单图形 版权声明 该文章原创于Qter开源社区,作者yafeilinux,转载请注明出处! 导语 Qt中提供了强大的2D绘图系统,可以使用相同的API在屏幕和绘图设备上进行绘制,它主要基于QPainter.QPaintDevice和QPaintEngine这三个类.其中QPainter用来执行绘图操作:QPaintDevice提供绘图设备,它是一个二

[OBJECT-C语言随笔之四]创建视图并绘制简单图形

本站文章均为 李华明Himi 原创,转载务必在明显处注明:  转载自[黑米GameDev街区] 原文链接: http://www.himigame.com/iphone-object/401.html 这段时间N忙,没办法,创业公司,当然抽时间也仍然再自学ios-OK,基础的语言基础,我就不多说了,从今天开始直接写游戏开发部分了: 声明一点:iOS游戏开发系列没有我写的Android游戏开发系列有权威性,因为我也是在学习中,只是拿出来给大家分享,希望大家不要较真,现在咱们都是一年级新生,咳咳,好

python opencv 绘制简单图形

09-python opencv 绘制简单图形 09-python opencv 绘制简单图形 概述 实现过程 引用与创建空图 绘制直线 绘制矩形 绘制圆 绘制椭圆 添加文字 显示图像 源代码 运行结果 参考 概述 本节实现的是使用OpenCV里自带的函数,绘制直线.长方形.圆形和椭圆. 绘制直线 绘制长方形 绘制圆形 绘制椭圆 添加文字 实现过程 引用与创建空图 不再赘述,代码如下. import cv2 import numpy # empty image img = np.zeros((5

Illustrator利用钢笔工具绘制闭合三角锥形教程

给各位Illustrator软件的使用者们来详细的解析分享一下利用钢笔工具绘制闭合三角锥形的教程. 教程分享: Illustrator的作用就是创建路径.用户可以用它来绘制描述线条和图形的数学算法矢量,这些描述在屏幕上以路径显示. 本章详细介绍了各种基本图形绘制工具的用法.使用这些工具,可以方便地绘制矩形.椭圆.多边形以及星形等基本图形,这些都是闭合路径;另外 , 还可以绘制如直线.曲线和螺旋线等各种开放路径图形. 值得注意的是Illustrator中的曲线绘制,由于Pierre Bezier的

《HTML5 Canvas游戏开发实战》——2.2 绘制复杂图形

2.2 绘制复杂图形 前面了解了基本图形的绘制方法,下面我们来看看复杂图形该如何绘制.2.2.1 画曲线贝塞尔曲线,又称贝兹曲线或贝济埃曲线,是应用于二维图形应用程序的数学曲线.在这里我们不研究贝塞尔曲线的原理,主要介绍在Canvas中如何绘制它.1 . 二次贝塞尔曲线二次贝塞尔曲线有一个控制点.在Canvas中用quadraticCurveTo(cpx,cpy,x,y)函数来绘制二次贝塞尔曲线,cpx.cpy表示控制点的坐标:x.y表示终点坐标.它的绘制如代码清单2-11所示.代码清单 2-1

TrackingLayer层绘制的图形对象怎么不保留啊?

问题描述 我利用vc6.0调试mapobjects组件,在TrackingLayer层绘制的图形对象怎么不保留啊?之前参考的是vb代码,map1.TrackingLayer.Refreshture这句话在vc里面怎么改啊?折腾了两天了,没有结果,请大神指导啊? 解决方案 解决方案二:你试试这样行不行.VARIANTva;VariantInit(&va)va.vt=VT_NULL;tLayer.Refresh(true,va);