Bézier curve is a cubic(立方体的) line. Bézier curve in PyQt5 can be created with QPainterPath. A painter path is an object composed of a number of graphical building blocks, such as rectangles, ellipses, lines, and curves.
代码:
# coding='utf-8'
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QPainterPath
from PyQt5.QtCore import Qt
import sys
class Gui(QWidget):
def __init__(self):
super(Gui, self).__init__()
self.start()
def start(self):
self.setGeometry(300, 300, 380, 250)
self.setWindowTitle('Bézier曲线')
self.show()
# 当主窗体size发生改变时就会触发这个slot\
# (窗体从无到有建立的过程也算是发生了改变)
def paintEvent(self, e) -> None:
qp = QPainter()
qp.begin(self)
# QPainter实例化对象的begin和end方法中间夹得就是绘制的过程\
# 注意begin有一个参数是代表绘制到哪里,而end没有
self.draw_bezier_curve(e, qp)
qp.end()
def draw_bezier_curve(self, e, qp):
# 实例化QPainterPath对象
# A painter path is an object composed of\
# a number of graphical building blocks,\
# such as rectangles, ellipses, lines, and curves.
path = QPainterPath()
# 从哪里开始绘制
path.moveTo(30, 30)
# 绘制曲线
# cubicTo构造函数:
"""
cubicTo(self, Union[QPointF, QPoint],\
Union[QPointF, QPoint], Union[QPointF, QPoint])
cubicTo(self, float, float, float, float, float, float)
"""
# 第二种构造函数: starting point, control point,\
# and ending point.
# 在这里就是(30, 30)开始, (200, 350)控制曲线形状, (350, 30)结束
path.cubicTo(30, 30, 200, 350, 350, 30)
# 绘制出最终的曲线,这里传递给QPainter对象的参数是QPainterPath实例化对象
qp.drawPath(path)
app = QApplication(sys.argv)
gui = Gui()
sys.exit(app.exec_())
运行结果:
image.png
网友评论