当我尝试通过 QThread 的帮助进行自我更新 QLineSeries 时遇到问题。
from PySide2.QtCore import *
from PySide2 import *
from PySide2.QtWidgets import *
from PySide2.QtCharts import *
from PySide2.QtGui import *
import time
baseValuesList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
randomValuesList = [256, 14, 89, 100, 150, 500, 50, 34, 67, 90, 102, 12, 19, 89, 34, 145, 71, 4, 89, 47]
rangeList = list(range(len(baseValuesList)))
def listUpdatingFunction():
baseValuesList.pop(0)
baseValuesList.append(randomValuesList[0])
randomValuesList.pop(0)
class Worker(QObject):
def __init__(self, function, interval):
super(Worker, self).__init__()
self._step = 0
self._isRunning = True
self.function = function
self.interval = interval
def task(self):
if not self._isRunning:
self._isRunning = True
self._step = 0
while self._isRunning == True:
self.function()
time.sleep(self.interval)
def stop(self):
self._isRunning = False
class minimalMonitor(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
# Creating QChart
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.chart = QtCharts.QChart()
self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)
self.series = QtCharts.QLineSeries()
for i in rangeList:
self.series.append(i,baseValuesList[i])
self.chart.addSeries(self.series)
self.chart_view = QtCharts.QChartView(self.chart)
self.chart_view.setRenderHint(QPainter.Antialiasing)
self.layout.addWidget(self.chart_view)
self.axis_x = QtCharts.QValueAxis()
self.chart.addAxis(self.axis_x, Qt.AlignBottom)
self.axis_y = QtCharts.QValueAxis()
self.chart.addAxis(self.axis_y, Qt.AlignLeft)
self.axis_x.setRange(0, 20)
self.axis_y.setRange(0, 300)
self.series.attachAxis(self.axis_x)
self.series.attachAxis(self.axis_y)
self.thread = QThread()
self.thread.start()
self.worker = Worker(self.update, 1)
self.worker.moveToThread(self.thread)
self.autoUpdateStart = QPushButton("Start Auto-Update")
self.autoUpdateStart.setCheckable(False)
self.autoUpdateStart.toggle()
self.autoUpdateStart.clicked.connect(self.worker.task)
self.autoUpdateStop = QPushButton("Stop Auto-Update")
self.autoUpdateStop.setCheckable(False)
self.autoUpdateStop.toggle()
self.autoUpdateStop.clicked.connect(lambda: self.worker.stop())
self.layout.addWidget(self.autoUpdateStart)
self.layout.addWidget(self.autoUpdateStop)
self.manualUpdateButton = QPushButton("Manual Update")
self.manualUpdateButton.setCheckable(False)
self.manualUpdateButton.toggle()
self.manualUpdateButton.clicked.connect(self.update)
self.layout.addWidget(self.manualUpdateButton)
def update(self):
listUpdatingFunction()
self.series.clear()
for i in rangeList:
self.series.append(i,baseValuesList[i])
self.chart_view.update()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
widget = minimalMonitor()
widget.show()
sys.exit(app.exec_())
简而言之,如果我直接调用更新函数或按手动更新,QLineSeries 将正确附加,但是一旦我使用 QThread 或自动更新按钮,它就会变得混乱,并且总是会尝试与轴原点连接。有谁知道为什么要这样做?