pyqt的pyqtgragh用多线程更新动态绘制曲线完整代码
时间: 2023-07-03 14:12:13 浏览: 458
这里是一个使用PyQtGraph进行多线程动态绘制曲线的完整代码示例:
```python
import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QThread, pyqtSignal
import numpy as np
import sys
class GraphThread(QThread):
update_signal = pyqtSignal(object)
def __init__(self, parent=None):
super(GraphThread, self).__init__(parent)
self.xdata = np.arange(100)
self.ydata = np.zeros((2, 100))
def run(self):
while True:
# 模拟数据更新
self.ydata[0, :] = np.random.normal(size=100)
self.ydata[1, :] = np.random.normal(size=100)
self.update_signal.emit(self.ydata)
self.msleep(50)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.graph_widget = pg.PlotWidget()
self.setCentralWidget(self.graph_widget)
self.curve1 = self.graph_widget.plot(pen='r')
self.curve2 = self.graph_widget.plot(pen='g')
self.graph_thread = GraphThread()
self.graph_thread.update_signal.connect(self.update_graph)
self.graph_thread.start()
def update_graph(self, ydata):
self.curve1.setData(self.graph_thread.xdata, ydata[0])
self.curve2.setData(self.graph_thread.xdata, ydata[1])
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
在这个例子中,我们使用了PyQtGraph的PlotWidget来绘制曲线。我们创建了一个GraphThread类来模拟数据更新,并使用update_signal信号将数据传递到主线程。在主线程中,我们将数据用于更新两个曲线(curve1和curve2)。请注意,在GraphThread类中,我们使用了msleep方法休眠线程以避免过度消耗CPU资源。
阅读全文