我正在尝试创建一个应用程序,我想要有几个PlotWidgets,用于绘制我在Arduino中最多5个传感器的信号。一旦我有两个更新图,GUI就不会响应,我需要暂停/重新启动绘图,并弹出一些值的警报。为了解决这个问题,我已经开始研究以使用QThread,但是对于PyQtGraph来说这可能是不可能的,因为我们不能在多个线程中完成绘图?我的两个PlotWidgets的代码如下:
from PyQt4 import QtCore, QtGui
import pyqtgraph as pg
import random
import sys
class MainWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
layout = QtGui.QHBoxLayout()
self.button = QtGui.QPushButton('Start Plotting Left')
layout.addWidget(self.button)
self.button.clicked.connect(self.plotter)
self.button2 = QtGui.QPushButton('Start Plotting Right')
layout.addWidget(self.button2)
self.button2.clicked.connect(self.plotter2)
self.plot = pg.PlotWidget()
layout.addWidget(self.plot)
self.plot2 = pg.PlotWidget()
layout.addWidget(self.plot2)
self.setLayout(layout)
def plotter(self):
self.data =[0]
self.curve = self.plot.getPlotItem().plot()
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.updater)
self.timer.start(0)
def updater(self):
self.data.append(self.data[-1]+0.2*(0.5-random.random()) )
self.curve.setData(self.data)#Downsampling does not help
def plotter2(self):
self.data2 =[0]
self.curve2 = self.plot2.getPlotItem().plot()
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.updater2)
self.timer.start(0)
def updater2(self):
self.data2.append(self.data[-1]+0.2*(0.5-random.random()) )
self.curve2.setData(self.data) #Downsampling does not help
if __name__ == '__main__':
app = QtGui.QApplication([])
window = MainWindow()
window.show()
app.exec_()
我准备好阅读并尝试QThread,但首先我需要知道是否可能,或者我是否在浪费我的日子和睡眠。有没有人暗示我怎么能让它发挥作用?
答案 0 :(得分:2)
您的代码有一些打印错误导致其无法正常工作
在updater2
内,您使用self.data
代替self.data2
。代码应该是:
def updater2(self):
self.data2.append(self.data2[-1]+0.2*(0.5-random.random()) )
self.curve2.setData(self.data2) #Downsampling does not help
此外,在创建第二个计时器时,将其存储在与第一个计时器相同的变量中,这会使其停止。更正后的代码应为:
def plotter2(self):
self.data2 =[0]
self.curve2 = self.plot2.getPlotItem().plot()
self.timer2 = QtCore.QTimer()
self.timer2.timeout.connect(self.updater2)
self.timer2.start(0)
请注意,在计时器启动后“启动”计时器(也就是单击同一个按钮两次)会导致程序崩溃。您可能应该禁用按钮,或者再次单击停止计时器或其他东西。这取决于你。
关于线程,你可以通过在另一个线程中读取arduino over serial中的数据来获得线程的一些性能提升(GUI不会锁定),但你需要通过PyQt发送数据发信号到主线程并在那里运行绘图命令。 StackOverflow上有很多关于如何使用PyQt正确连接的例子(例如here)