使用 QTimer 更新 PlotWidget 的自定义 AxisItem

问题描述

我的目标是创建一个 gui,其中包含每隔几秒更新一次的多个图和值。我希望 x 轴显示时间。我设法用 AxisItem 做到了这一点,但是当新值添加到图中时,我的 AxisItems 不会更新。我可以理解为什么,我应该在 def getSensorValue(self): 方法中有一些代码。为了让它看起来不错,我只希望每第 5 个轴刻度显示时间。有没有简单的方法来做到这一点?我用一个用“”替换 4 次的循环实现了它,这可行,但也许有更简单的方法?

这是一个简化的代码,它生成随机值以使其更简单。 “真正的”程序从 mqtt 服务器接收值,但这应该无关紧要。

import PyQt5.QtWidgets as qtw
import pyqtgraph as pg
from datetime import datetime
import time
import random
from PyQt5.QtCore import QTimer

class MainWindow(qtw.QMainWindow):
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle('DemoPlot')
        self.resize(800,800)
        self.setLayout(qtw.QVBoxLayout())

        self.x= list()
        self.y = list()
        i=0
        
        while i<20:            
            self.x.append(datetime.now().strftime("%H:%M:%S"))
            time.sleep(0.01)
            i=i+1
            self.y.append(i)
            
        self.xdict = dict(enumerate(self.x))
        
        self.qTimer(1000)
        
        # Luftdruck Graph
        self.plot_Luftdruck,self.data_Luftdruck = self.makePlot(self.xdict,self.y)

        
        self.keypad()
        
        self.show()
                
    def makePlot(self,x_Values,y_Values):
        plot = pg.PlotWidget()
        plot.setBackground('w')
        stringaxis = pg.AxisItem(orientation='bottom')
        stringaxis.setTicks([x_Values.items()])
        plot.setAxisItems(axisItems={'bottom': stringaxis})
        pen = pg.mkPen(color=(255,0))
        data=plot.plot(list(x_Values),y_Values,pen=pen)
        return plot,data
    
    def qTimer(self,interval):
        # make QTimer
        self.qTimer = QTimer()
        # set interval to 1 s
        self.qTimer.setInterval(interval) # 1000 ms = 1 s
        # connect timeout signal to signal handler
        self.qTimer.timeout.connect(self.getSensorValue)
        # start timer
        self.qTimer.start()
        
    
    def getSensorValue(self):
        #Luftdruck Graph
        self.y.append(round(random.uniform(-3,3),4))
        self.x.append(datetime.now().strftime("%H:%M:%S"))
        self.xdict = dict(enumerate(self.x))
        
        self.data_Luftdruck.setData(list(self.xdict),self.y)
        
    def closeEvent (self,event):
        self.sub.disconnect()
        
      
    def keypad(self):
                    
        container = qtw.QWidget()
        container.setLayout(qtw.QGridLayout())
        
        container.layout().addWidget(self.plot_Luftdruck,2,5,3,3)
               
        self.layout().addWidget(container)        
        
app = qtw.QApplication([])
mw = MainWindow()
app.setStyle(qtw.QStyleFactory.create('Fusion'))
app.exec_()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)