@Anonimista
atexit.register registered functions/methods are executed on the Python interpreter termination a better solution would be to use weakref.finalize which is called when a LineChart is garbage collected. Here is the current code:
import sys
import psutil
import weakref
from PySide6.QtCore import (Qt, QTimer, QThread,QObject,
Signal, Slot)
from PySide6.QtGui import QPainter
from PySide6.QtWidgets import (QMainWindow, QApplication,
QWidget, QHBoxLayout)
from PySide6.QtCharts import QChart, QChartView, QLineSeries
class Worker(QObject):
done = Signal(int)
def __init__(self, parent=None):
super().__init__(parent)
@Slot()
def get_cpu_load(self):
if QThread.currentThread().isInterruptionRequested():
return
self.done.emit(psutil.cpu_percent())
class LineChart(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
weakref.finalize(self, self.cleanup)
self.worker = Worker()
self.thread = QThread()
self.worker.moveToThread(self.thread)
self.thread.start()
self.series = QLineSeries()
for i in range(10):
self.series.append(i, 0)
self.chart = QChart()
self.chart.legend().hide()
self.chart.addSeries(self.series)
self.chart.createDefaultAxes()
self.chart.setTitle('CPU load')
self.chart.layout().setContentsMargins(0, 0, 0, 0)
self.chart.setBackgroundRoundness(0)
self.horizontal_axis = self.chart.axes(Qt.Orientation.Horizontal)[0]
self.vertical_axis = self.chart.axes(Qt.Orientation.Vertical)[0]
self.horizontal_axis.setLabelsVisible(False)
self.vertical_axis.setLabelsVisible(False)
self.vertical_axis.setMin(0)
self.vertical_axis.setMax(100)
self.chart_view = QChartView(self.chart)
self.chart_view.setRenderHint(QPainter.Antialiasing)
self.setLayout(QHBoxLayout())
self.layout().addWidget(self.chart_view)
self.timer = QTimer()
self.timer.timeout.connect(self.worker.get_cpu_load)
self.worker.done.connect(self.update_chart)
self.timer.start(500)
self.current_time = 19
def update_chart(self, load):
self.series.append(self.current_time, load)
self.current_time += 1
if self.series.count() > 20:
self.series.remove(0)
self.horizontal_axis.setMin(self.series.at(0).x())
self.horizontal_axis.setMax(self.series.at(self.series.count() - 1).x())
def cleanup(self):
print('in cleanup')
self.timer.stop()
self.thread.requestInterruption()
self.thread.quit()
self.thread.wait()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.chart_widget = LineChart()
self.setCentralWidget(self.chart_widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.resize(440, 300)
window.show()
sys.exit(app.exec())