pyqt6 使用qcharts绘制曲线示例
时间: 2023-10-24 17:19:23 浏览: 387
非常感谢您的提问。这是一个很好的问题。这里提供一个简单的示例,用于使用PyQt6和QCharts绘制曲线。
```
import sys
from PyQt6.QtCore import Qt
from PyQt6.QtGui import *
from PyQt6.QtWidgets import QApplication, QMainWindow, QChartView, QValueAxis, QLineSeries, QVBoxLayout, QHBoxLayout, QWidget
from PyQt6.QtCharts import QtCharts
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt6 QChart Example")
# create chart and set general options
self.chart = QtCharts.QChart()
self.chart.setTitle("Chart Title")
self.chart.setAnimationOptions(QtCharts.QChart.SeriesAnimations)
# create xaxis and set general options
axisX = QtCharts.QValueAxis()
axisX.setLabelFormat("%d")
axisX.setTitleText("X Axis Title")
axisX.setTickCount(10)
axisX.setRange(0, 10)
# create yaxis and set general options
axisY = QtCharts.QValueAxis()
axisY.setLabelFormat("%.2f")
axisY.setTitleText("Y Axis Title")
axisY.setRange(0, 100)
# create line series and add it to chart
series = QtCharts.QLineSeries()
series.setName("Line Series")
# add data to line series
series.append(0, 10)
series.append(1, 20)
series.append(2, 30)
series.append(3, 40)
series.append(4, 50)
series.append(5, 60)
series.append(6, 70)
series.append(7, 80)
series.append(8, 90)
series.append(9, 100)
# add series to chart
self.chart.addSeries(series)
# set xaxis and yaxis to chart
self.chart.setAxisX(axisX, series)
self.chart.setAxisY(axisY, series)
# create vertical layout and chart view
layout = QVBoxLayout()
chartView = QChartView(self.chart)
chartView.setRenderHint(QPainter.Antialiasing)
# add chart view to layout
layout.addWidget(chartView)
# create horizontal layout and add widgets
hbox = QHBoxLayout()
widget = QWidget()
widget.setLayout(hbox)
# add layout to horizontal layout
hbox.addLayout(layout)
# set central widget of main window
self.setCentralWidget(widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
```
这个示例创建了一个带有标题和x,y轴标签的图表。它使用QValueAxis来设置X和Y轴,并使用QLineSeries来绘制曲线。数据通过调用series.append()方法添加到曲线上。最后,QChartView用于绘制图表,并将其添加到主窗口中。
希望这个示例可以帮助你入门PyQt6和QCharts。如果您有任何其他问题,请随时问我。
阅读全文