Cao Lin's Blog.

记一次基于PyQtGraph上位机开发

Word count: 302Reading time: 1 min
2020/09/22 Share

需求

  • 1、能够导入txt数据文件,并且绘制图形
  • 2、能够使用鼠标选择部分曲线区域,并且放大该区域

最终结果

2020-09-22 131228

如图所示,将绘图部分图像分为两部分,上半部分为原始曲线,可以选择相应的区域,在下方放大显示。

实现思路

  • 使用qt creator创建ui界面,使用一个Vertical Layout作为PyQtGraph的容器
1
2
self.win = pg.GraphicsLayoutWidget() #创建PyQtGraph的画图窗口
self.PlotLayout.addWidget(self.win) #将画图窗口添加到我们之前设置的`Vertical Layout`中,此处为PlotLayout
  • 使用pyuic将ui文件转换为py文件
1
python -m PyQt5.uic.pyuic mainwindow.ui -o mainwindow.py
  • 添加两个上下位置的PyQtGraph画布
1
2
3
p1 = self.win.addPlot(title="xxx")  # 添加第一个绘图窗口
self.win.nextRow() # layout换行,采用垂直排列,不添加此行则默认水平排列
p2 = self.win.addPlot(title="yyy")
  • 添加区域选择控件
1
2
3
4
self.LinRegionItem = pg.LinearRegionItem([0,20])
self.raw_graph.addItem(self.LinRegionItem)

self.Zoom_graph.sigXRangeChanged.connect(self.updateRegion) #区域变化时触发updateRegion()函数
  • 读取当前区域的首尾索引,设置曲线x轴范围
1
2
3
4
start_index = int(self.LinRegionItem.getRegion()[0])
end_index = int(self.LinRegionItem.getRegion()[1])

self.Zoom_graph.setXRange(start_index, end_index, padding=0)

TODO

异常处理

CATALOG
  1. 1. 需求
  2. 2. 最终结果
  3. 3. 实现思路
  4. 4. TODO