用线程更新动态pyqt的pyqtgragh绘制曲线完整代码
时间: 2023-10-24 20:32:01 浏览: 258
好的,下面是一个完整的使用线程更新动态PyQtGraph绘制曲线的示例程序:
```python
import sys
import numpy as np
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow
import pyqtgraph as pg
class UpdateThread(QThread):
data_generated = pyqtSignal(object)
def run(self):
x = np.linspace(0, 10, 1000)
counter = 0
while True:
y = np.sin(x + counter / 10.0)
self.data_generated.emit((x, y))
counter += 1
self.msleep(10)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建PlotWidget
self.plot_widget = pg.PlotWidget()
self.setCentralWidget(self.plot_widget)
# 创建曲线
self.curve = pg.PlotCurveItem()
self.plot_widget.addItem(self.curve)
# 创建UpdateThread线程
self.update_thread = UpdateThread()
# 将曲线对象与数据更新信号连接起来
self.update_thread.data_generated.connect(self.update_plot)
# 启动线程
self.update_thread.start()
# 初始化x和y数组
self.x = np.array([])
self.y = np.array([])
def update_plot(self, data):
x, y = data
self.x = np.append(self.x, x)
self.y = np.append(self.y, y)
self.curve.setData(self.x, self.y)
self.plot_widget.setXRange(self.x[-1] - 10, self.x[-1])
# 创建应用程序
app = QApplication(sys.argv)
# 创建主窗口
main_window = MainWindow()
# 显示主窗口
main_window.show()
# 运行应用程序
sys.exit(app.exec_())
```
在这个示例程序中,我们首先创建了一个继承自QThread的UpdateThread类,用于生成随机数据并发送数据更新信号。
然后,我们创建了一个继承自QMainWindow的MainWindow类,用于创建PyQtGraph PlotWidget并将曲线对象添加到其中。
接着,我们将曲线对象与UpdateThread线程中的数据更新信号连接起来,并启动线程。
在MainWindow类中,我们定义了一个update_plot方法,用于在接收到数据更新信号时更新曲线的数据和范围。在这个方法中,我们使用numpy库中的append方法将新的数据添加到x和y数组中,并使用setData方法将新的数据更新到曲线对象中。我们还使用setXRange方法将x轴的范围设置为最新的数据范围。
最后,我们运行应用程序并显示主窗口,程序将在主窗口中显示一个动态的PyQtGraph曲线,并使用线程来更新曲线的数据。
希望这个示例程序可以对您有所帮助!
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)