使用QML-qtquick 进行开发时,有个使用chart图表的需求,看了一大圈,网上都是qmake或是cmake来构建QTchart,用python开发也只搜到QtWidgets模块进行图表绘制。然而我对qtwidgets不是很了解,想要的是QML开发,在使用ChartView{}
时一直闪退,没有效果。经历了苦苦搜寻,终于在 https://stackoverflow.com/questions/57536401/how-to-add-qml-scatterseries-to-existing-qml-defined-chartview/57541374#57541374 这个文章下搜寻到我想要的了。
python文件
import sys
from PySide6 import QtWidgets, QtQmlif __name__ == "__main__":#一定要使用QtWidgets#app = QGuiApplication().instance()app = QtWidgets.QApplication(sys.argv)engine = QtQml.QQmlApplicationEngine()engine.load("main.qml")if not engine.rootObjects():sys.exit(-1)sys.exit(app.exec())
main.qml
import QtQuick
import QtQuick.Controls
import QtChartsApplicationWindow {visible: truewidth: 640height: 480Rectangle{width:640height:80anchors.top:parent.topcolor:"pink"Text{anchors.centerIn:parenttext:'折线图'}}Rectangle {width:640height:400anchors.bottom:parent.bottomChartView {title: "Line Chart"anchors.fill: parentantialiasing: trueLineSeries {name: "Line"XYPoint { x: 0; y: 0 }XYPoint { x: 1.1; y: 2.1 }XYPoint { x: 1.9; y: 3.3 }XYPoint { x: 2.1; y: 2.1 }XYPoint { x: 2.9; y: 4.9 }XYPoint { x: 3.4; y: 3.0 }XYPoint { x: 4.1; y: 3.3 }}}}
}
这样就能愉快的使ChartView{}
绘制图表了
官网例子:https://doc.qt.io/qt-6/qtcharts-qmlchartsgallery-example.html
下面是图表与python数据交互
折线图
python
import sys
import random
from PySide6 import QtCore,QtWidgets, QtQml, QtChartsclass DataModel(QtCore.QObject):@QtCore.Slot(QtCharts.QAbstractSeries)def fill_serie(self, serie):for x in range(10): # 10 个数据点y = random.randint(0, 100) # 随机 y 值serie.append(x, y) # 添加数据点if __name__ == "__main__":app = QtWidgets.QApplication(sys.argv)engine = QtQml.QQmlApplicationEngine()data_model = DataModel()engine.rootContext().setContextProperty("dataModel", data_model)engine.load("main.qml")if not engine.rootObjects():sys.exit(-1)sys.exit(app.exec())
main.qml
import QtQuick
import QtQuick.Controls
import QtChartsApplicationWindow {visible: truewidth: 640height: 480Rectangle{width:640height:80anchors.top:parent.topcolor:"pink"Text{anchors.centerIn:parenttext:'折线图'}}Rectangle {width:640height:400anchors.bottom:parent.bottomChartView {anchors.fill: parentid: chartView// 定义 X 轴和 Y 轴ValueAxis {id: xAxismin: 0max: 10}ValueAxis {id: yAxismin: 0max: 100}Component.onCompleted: {// 创建折线图系列var serie = chartView.createSeries(ChartView.SeriesTypeLine, "line series", xAxis, yAxis);// 填充数据dataModel.fill_serie(serie);}}}
}
持续刷新可以加个定时器。Timer