I want to make an application that put a random point on a graph every 5 seconds but it does not update when I append the point to the line series. I also tried the repaint() and QApplication.ProcessEvent() but still does not update.
here's my code
import random
from PySide6 import QtCore, QtWidgets
from PySide6.QtCharts import QChartView, QChart, QLineSeries
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.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}")
self.repaint()
self.chart_view.repaint()
QtWidgets.QApplication.processEvents()
if __name__ == "__main__":
app = QtWidgets.QApplication()
graph = MyGraph()
graph.show()
app.exec_()
I want to add points every 5 seconds and update the graph.
The graph does not update but the points is appended to the line series.
here's the workaround
import random
from PySide6 import QtCore, QtWidgets
from PySide6.QtCharts import QChartView, QChart, QLineSeries
class MyGraph(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.points = []
# Set up the graph
self.point_line_series = QLineSeries()
chart = QChart()
chart.addSeries(self.point_line_series)
chart.setTitle("Points Over Time")
self.chart_view = QChartView()
self.chart_view.setChart(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}")
chart = QChart()
chart.addSeries(self.point_line_series)
self.chart_view.setChart(chart)
if __name__ == "__main__":
app = QtWidgets.QApplication()
graph = MyGraph()
graph.show()
app.exec_()
basically just make a new chart add the line series and set that chart as the chart of chart view using chart.setchart()