首页 > 解决方案 > 如何动态更新 PyQt 条形图?

问题描述

我正在尝试动态创建和更新条形图。我能够创建图表,但是在尝试动态更新它时出现以下错误。

图表是使用QChart创建的。获取来自端口的所有数据的以下错误,并在最后显示图表而不进行任何动态更新。错误说无法添加系列。系列已经在图表上

下面给出的代码。我是 python 和 PyQt5 的新手,任何线索将不胜感激。

class MainWindow(QMainWindow):
def __init__(self):
    super().__init__()
    self.resize(800, 600)

    self.s = serial.Serial('/dev/pts/1', 9600, timeout=None, parity=serial.PARITY_NONE,
                           stopbits=serial.STOPBITS_ONE,
                           bytesize=serial.EIGHTBITS)

    self.set0 = QBarSet('Count')

    # set0.append([random.randint(0, 999) for i in range(3)])

    self.series = QBarSeries()
    # self.series.append(self.set0)

    self.chart = QChart()
    # self.chart.addSeries(self.series)
    self.chart.setTitle('Bar Chart Demo')
    self.chart.setAnimationOptions(QChart.SeriesAnimations)

    months = ('Diamond', 'Hexagon', 'Trapezium')

    axisX = QBarCategoryAxis()
    axisX.append(months)

    axisY = QValueAxis()
    axisY.setRange(0, 1000)

    self.chart.addAxis(axisX, Qt.AlignBottom)
    self.chart.addAxis(axisY, Qt.AlignLeft)

    self.chart.legend().setVisible(True)
    self.chart.legend().setAlignment(Qt.AlignBottom)

    self.chartView = QChartView(self.chart)

    self.setCentralWidget(self.chartView)
    self.drawGraph()

def drawGraph(self):
    timeout = 50
    timeout_start = time.time()
    while time.time() < timeout_start + timeout:
        time.sleep(1)
        cc = self.s.read(15)
        ccread = cc.decode("utf-8")
        print(ccread)
        diamond = ccread[1:4]
        hexa = ccread[6:9]
        trep = ccread[11:14]
        self.set0.append(int(diamond))
        self.set0.append(int(hexa))
        self.set0.append(int(trep))
        self.series.append(self.set0)
        self.chart.addSeries(self.series)

标签: pythonpyqt5qtcharts

解决方案


推荐阅读