import pyqtgraph as pgimport timeplt = pg.plot()def update(data):plt.plot(data, clear=True)class Thread(pg.QtCore.QThread):newData = pg.QtCore.Signal(object)def run(self):while True:data = pg.np.random.normal(size=100)
# do NOT plot data from here!
self.newData.emit(data)time.sleep(0.05)thread = Thread()thread.newData.connect(update)thread.start()
Here's a simple example using QThread: (the equivalent using python's threading looks very similar)import pyqtgraph as pgimport timeplt = pg.plot()def update(data):plt.plot(data, clear=True)class Thread(pg.QtCore.QThread):newData = pg.QtCore.Signal(object)def run(self):while True:data = pg.np.random.normal(size=100)# do NOT plot data from here!self.newData.emit(data)time.sleep(0.05)thread = Thread()thread.newData.connect(update)thread.start()
Here's a simple example using QThread: (the equivalent using python's threading looks very similar)
[snip]
Thanks. That indeed does seem pretty simple.Next question: While this works for the simple display of the data later I want to allow the user to change a few settings that will get sent back to the device via the serial port. I was going to connect those up to various pyqtgraph gui controls. Will it be equally simple to send those events back to the serial thread or will that be a lot more complex?
import pyqtgraph as pgimport threading
import timeplt = pg.plot()def update(data):plt.plot(data, clear=True)class Thread(pg.QtCore.QThread):newData = pg.QtCore.Signal(object)
def __init__(self):super(Thread, self).__init__()self.stopMutex = threading.Lock()self._stop = Falsedef run(self):while True:# Must protect self._stop with a mutex because the main thread# might try to access it at the same time.with self.stopMutex:if self._stop:# causes run() to exit, which kills the thread.breakdata = pg.np.random.normal(size=100)self.newData.emit(data)time.sleep(0.05)def stop(self):# Must protect self._stop with a mutex because the secondary thread# might try to access it at the same time.with self.stopMutex:self._stop = True
thread = Thread()thread.newData.connect(update)thread.start()
stopBtn = pg.QtGui.QPushButton("Stop")stopBtn.setParent(plt)stopBtn.show()stopBtn.clicked.connect(thread.stop)
Below, I have extended the previous example to include a button to stop the updates. Things of note: