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

PySide6问题:向Chart View动态添加点后图表不更新

问题原因

你的代码里没有为QChart添加坐标轴,QChart不会自动为QLineSeries生成默认坐标轴,导致即使向系列中添加了数据点,图表也无法正确渲染显示这些点。你调用的repaint()和processEvents()方法并不是问题的关键,核心缺失的是坐标轴的配置。

解决方法

在初始化图表时,创建数值坐标轴(QValueAxis),将其添加到图表中,并把折线系列关联到坐标轴上。这样当系列数据更新时,图表会自动更新显示,无需手动调用重绘方法。

修改后的完整代码
import random
from PySide6 import QtCore, QtWidgets
from PySide6.QtCharts import QChartView, QChart, QLineSeries, QValueAxis


class MyGraph(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.points = []

        # Set up the graph
        self.point_line_series = QLineSeries()
        self.chart = QChart()
        self.chart.addSeries(self.point_line_series)
        self.chart.setTitle("Points Over Time")
        
        # 添加并配置坐标轴
        self.axis_x = QValueAxis()
        self.axis_y = QValueAxis()
        # 设置坐标轴范围(可选,也可以让图表自动调整)
        self.axis_x.setRange(0, 100)
        self.axis_y.setRange(0, 100)
        self.chart.addAxis(self.axis_x, QtCore.Qt.AlignBottom)
        self.chart.addAxis(self.axis_y, QtCore.Qt.AlignLeft)
        # 将系列关联到坐标轴
        self.point_line_series.attachAxis(self.axis_x)
        self.point_line_series.attachAxis(self.axis_y)

        self.chart_view = QChartView()
        self.chart_view.setChart(self.chart)

        self.setCentralWidget(self.chart_view)

        # Start a timer to add new points every 5 seconds
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.add_point)
        self.timer.start(5000)

    def add_point(self):
        x = random.randint(0, 100)
        y = random.randint(0, 100)
        self.points.append((x, y))
        self.point_line_series.append(x, y)
        print(f"added point {x}, {y}")
        # 不需要手动调用重绘,数据变化会自动触发图表更新


if __name__ == "__main__":
    app = QtWidgets.QApplication()
    graph = MyGraph()
    graph.show()
    app.exec_()
关键说明
  • 添加QValueAxis并关联到系列后,图表就能识别数据的坐标范围,正确渲染折线和点。
  • 如果不想固定坐标轴范围,可以去掉setRange调用,图表会根据新增的点自动调整坐标轴的显示范围。
  • 移除了不必要的repaint()和processEvents()调用,因为QtCharts组件会自动响应数据变化并更新UI。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:55:32