You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python将数组数据一次性传入QML Qt Charts绘图

一次性将Numpy数组数据传入QML Qt Charts的高效方案

方案一:批量传递数据列表(快速实现)

Python端修改

修改信号定义为可传递两个列表,将Numpy数组转为Python列表后一次性发送:

from PySide6.QtCore import QObject, Signal
import numpy as np

class AppWindow(QObject):
    # 定义传递批量数据的信号
    sigPlotBatchData = Signal(list, list, arguments=['xData', 'yData'])

# 准备Numpy数据
x = np.array([0, 1, 2, 3, 4, 5, 6])
y = np.array([0, 100, 150, 200, 180, 220, 250])

# 转换为Python列表并发送信号
self.app.sigPlotBatchData.emit(x.tolist(), y.tolist())

QML端接收处理

接收批量数据后,清空原有数据并批量添加,可自动更新坐标轴范围:

Connections {
    target: backend

    function onSigPlotBatchData(xData, yData) {
        // 清空原有数据
        lineSer.clear();
        // 批量添加所有数据点
        for (let i = 0; i < xData.length; i++) {
            lineSer.append(xData[i], yData[i]);
        }
        // 自动更新坐标轴范围(可选)
        axisX.min = Math.min(...xData);
        axisX.max = Math.max(...xData);
        axisY.min = Math.min(...yData);
        axisY.max = Math.max(...yData);
    }
}

方案二:使用QAbstractListModel(适合大数据量/Qt最佳实践)

通过模型绑定的方式,让LineSeries直接从模型读取数据,无需手动append,数据更新时自动同步。

Python端实现模型

创建自定义列表模型,封装Numpy数据:

from PySide6.QtCore import QAbstractListModel, Qt, QModelIndex
import numpy as np

class PlotDataModel(QAbstractListModel):
    XRole = Qt.UserRole + 1
    YRole = Qt.UserRole + 2

    def __init__(self, parent=None):
        super().__init__(parent)
        self._data = []

    def rowCount(self, parent=QModelIndex()):
        return len(self._data)

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or index.row() >= len(self._data):
            return None
        x_val, y_val = self._data[index.row()]
        if role == self.XRole:
            return x_val
        elif role == self.YRole:
            return y_val
        return None

    def roleNames(self):
        return {
            self.XRole: b'x',
            self.YRole: b'y'
        }

    def updateData(self, x_array, y_array):
        if len(x_array) != len(y_array):
            return False
        self.beginResetModel()
        self._data = list(zip(x_array.tolist(), y_array.tolist()))
        self.endResetModel()
        return True

# 在AppWindow中持有模型实例
class AppWindow(QObject):
    def __init__(self):
        super().__init__()
        self.plot_model = PlotDataModel()

# 设置数据并将模型注册到QML上下文
x = np.array([0, 1, 2, 3, 4, 5, 6])
y = np.array([0, 100, 150, 200, 180, 220, 250])
self.app.plot_model.updateData(x, y)
# 注册模型到QML,让QML可以直接访问
engine.rootContext().setContextProperty("plotModel", self.app.plot_model)

QML端绑定模型

LineSeries直接绑定模型,指定x、y字段对应模型角色:

ChartView {
    id: chartView
    title: "Line"
    anchors.fill: parent

    ValueAxis{
        id: axisX
        min: 0
        max: 6
        // 可选:自动计算范围,需结合模型数据处理
    }

    ValueAxis{
        id: axisY
        min: 0
        max: 250
    }

    LineSeries {
        id: lineSer
        name: "data"
        axisX: axisX
        axisY: axisY
        // 绑定自定义模型
        model: plotModel
        // 指定模型中对应x、y数据的角色名称
        xField: "x"
        yField: "y"
    }
}

方案对比

  • 方案一:实现简单,代码改动小,适合中小规模数据,直接批量传递数据后手动添加。
  • 方案二:符合Qt MVVM架构,数据更新时自动同步图表,适合大数据量场景,后续数据维护更便捷。

内容的提问来源于stack exchange,提问作者WITC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:16:05