我实时画了一个pyqtgraph,通过Python做成一个小部件来测试它是否真的有效。结果,可以得到如下图所示的实时运行的图表,并确认x轴也更改为数据时间并正确显示。
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import *
import pyqtgraph as pg
import time
class TimeAxisItem(pg.AxisItem):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setLabel(text='Time(s)', units=None)
self.enableAutoSIPrefix(False)
def tickStrings(self, values, scale, spacing):
return [time.strftime("%H:%M:%S", time.localtime(local_time)) for local_time in values]
class ExampleWidget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.pw = pg.PlotWidget(
title="Example plot",
labels={'left': 'y'},
axisItems={'bottom': TimeAxisItem(orientation='bottom')}
)
hbox = QHBoxLayout()
hbox.addWidget(self.pw)
self.setLayout(hbox)
self.pw.setYRange(0, 70, padding=0)
time_data = int(time.time())
self.pw.showGrid(x=True, y=True)
self.pdi = self.pw.plot(pen='y')
self.plotData = {'x': [], 'y': []}
def update_plot(self, new_time_data: int):
data_sec = time.strftime("%S", time.localtime(new_time_data))
self.plotData['y'].append(int(data_sec))
self.plotData['x'].append(new_time_data)
self.pw.setXRange(new_time_data - 10, new_time_data + 1, padding=0)
self.pdi.setData(self.plotData['x'], self.plotData['y'])
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
ex = ExampleWidget()
def get_data():
new_time_data = int(time.time())
ex.update_plot(new_time_data)
mytimer = QTimer()
mytimer.start(1000)
mytimer.timeout.connect(get_data)
ex.show()
sys.exit(app.exec_())
结果:
现在我想在 qt desginer 的 graphicsView 小部件中表达上述代码的结果,而不是 Python 小部件。由于我的努力,我可以看到 Python 代码是使用 uic 模块导入到代码中的,如下面的代码所示。
form_class = uic.loadUiType("example.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
有一个ui叫做example.ui,其中有一个graphicsView提升为pyqtgraph。现在我想知道如何插入我在这里写的实时图表。
努力了很久,但找不到合适的解决方案,所以向stackoverflow的专家提出了这个问题。这是我第一次写问题,所以感谢您阅读到这里。