pyqt在QGraphicsView演示曲线图
时间: 2024-02-02 19:05:42 浏览: 33
以下是一个简单的PyQt代码示例,用于在QGraphicsView中绘制曲线图:
```
import sys
from PyQt5.QtCore import Qt, QPointF
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtWidgets import QApplication, QGraphicsScene, QGraphicsView
class CurveWidget(QGraphicsView):
def __init__(self, parent=None):
super(CurveWidget, self).__init__(parent)
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.setRenderHint(QPainter.Antialiasing)
self.data = [(0, 0), (1, 1), (2, 2), (3, 1), (4, 0.5), (5, 1.5)]
def drawCurve(self):
pen = QPen(Qt.red, 2, Qt.SolidLine)
path = QPainterPath()
path.moveTo(*self.data[0])
for i in range(len(self.data) - 1):
p1 = QPointF(*self.data[i])
p2 = QPointF(*self.data[i+1])
c1 = QPointF(p1.x() + 0.33 * (p2.x() - p1.x()), p1.y() + 0.33 * (p2.y() - p1.y()))
c2 = QPointF(p1.x() + 0.67 * (p2.x() - p1.x()), p1.y() + 0.67 * (p2.y() - p1.y()))
path.cubicTo(c1, c2, p2)
self.scene.addPath(path, pen)
if __name__ == '__main__':
app = QApplication(sys.argv)
curveWidget = CurveWidget()
curveWidget.show()
curveWidget.drawCurve()
sys.exit(app.exec_())
```
在此示例中,我们创建了一个名为CurveWidget的自定义QWidget类,并从QGraphicsView派生该类。我们使用QGraphicsScene来管理图形项,并在构造函数中将其添加到视图中。
我们的数据是一个包含一些点的列表。在drawCurve方法中,我们使用QPainterPath和QPointF对象来绘制曲线。我们使用cubicTo方法将贝塞尔曲线添加到路径中。最后,我们使用QGraphicsScene的addPath方法将路径添加到场景中。
在主函数中,我们创建一个应用程序实例,显示我们的CurveWidget,并调用drawCurve方法以绘制曲线。最后,我们开始Qt应用程序事件循环。