当绘图到达 QChartView 边框时如何滚动视图



我想创建一个动态图表,当绘图到达其可见边界时,它将移动图表视图。不幸的是,我不知道如何检测何时应该移动视图。

顺便说一句,scroll方法应该适用于移动视图(据我所知(,但即使我尝试scroll(1000, 0)也没有可见的结果

这是我的小部件类

from PySide2 import QtGui, QtWidgets, QtCore
from PySide2.QtCharts import QtCharts
from psutil import cpu_percent
import sys

class cpu_chart(QtCharts.QChart):
def __init__(self, input_data=None, parent=None):
super().__init__(parent)
self.axisX = QtCharts.QValueAxis()
self.axisY = QtCharts.QValueAxis()
self.axisX.setVisible(False)
self.step = 0
self.x = 0
self.y = 0
self.timer = QtCore.QTimer()
self.timer.setInterval(100)
self.timer.timeout.connect(self.onTimeout)
self.m_series = QtCharts.QSplineSeries()
pen = QtGui.QPen(QtCore.Qt.green)
pen.setWidth(1)
self.m_series.setPen(pen)
self.m_series.append(self.x, self.y)
self.addSeries(self.m_series)
self.addAxis(self.axisX, QtCore.Qt.AlignBottom)
self.addAxis(self.axisY, QtCore.Qt.AlignLeft)
self.m_series.attachAxis(self.axisX)
self.m_series.attachAxis(self.axisY)

self.axisX.setRange(0, 100)
self.axisY.setTickCount(5)
self.axisY.setRange(0, 100)
self.timer.start()
def onTimeout(self):
self.x += 1
self.y = cpu_percent()
self.m_series.append(self.x, self.y)
self.scroll(10, 0)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QMainWindow()
chart = cpu_chart()
chart.legend().hide()
chart.setAnimationOptions(QtCharts.QChart.AllAnimations)
chart_view = QtCharts.QChartView(chart)
chart_view.setRenderHint(QtGui.QPainter.Antialiasing)
window.setCentralWidget(chart_view)
window.resize(400, 300)
window.show()
sys.exit(app.exec_())

必须更改 X 轴的范围。

  • 如果要显示所有数据:
def onTimeout(self):
self.x += 1
self.y = cpu_percent()
self.m_series.append(self.x, self.y)
self.axisX.setRange(0, self.x)
  • 如果要显示最新的 N 个数据:
def onTimeout(self):
self.x += 1
self.y = cpu_percent()
self.m_series.append(self.x, self.y)
N = 100
self.axisX.setRange(max(0, self.x - N), self.x)

相关内容

  • 没有找到相关文章

最新更新