0 前期教程
- 【Python】PyQt5入門
1 前言
??最近在用PyQt做一個串口上位機,需要串口通信和實時顯示曲線。這里簡單記錄一些關(guān)鍵點。
2 串口部分——QtSerialPort
??這個是在安裝PyQt5時自動安裝的組件,使用方法比較簡單,主要是兩個模塊:QSerialPort
, QSerialPortInfo
# 導(dǎo)入包
from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
#獲取當(dāng)前的所有串口,得到一個列表
portlist = QSerialPortInfo.availablePorts()
#獲取串口的名稱和描述
l = [x.portName()+x.description() for x in self.portlist]
#建立一個串口,里面的參數(shù)可以填串口名或者就是串口類
ser = QSerialPort()
#接收數(shù)據(jù)對應(yīng)調(diào)用的函數(shù)
ser.readyRead.connect(recv_data)
#設(shè)置串口
def init_port(self, port:QSerialPort):
port.setBaudRate(self.baud)
port.setDataBits(QSerialPort.DataBits.Data8)
port.setParity(QSerialPort.Parity.NoParity)
port.setStopBits(QSerialPort.StopBits.OneStop)
port.readyRead.connect(recv_data)
#數(shù)據(jù)接收
data = ser.readAll().data() #得到的是字節(jié)字符串
??以上就是串口部分的代碼,比較簡單,利用代碼提示基本沒有什么問題。
關(guān)于字節(jié)字符串的處理可以看一下這篇文章
- 【學(xué)習(xí)筆記】字節(jié)數(shù)據(jù)和字節(jié)字符串(b“ “)那些事
3 繪圖部分
??經(jīng)過調(diào)研,發(fā)現(xiàn)在Qt當(dāng)中繪制函數(shù)曲線,常用的有3個包,分別是QCustomPlot
, QWT
和QtChart
,其中前兩者都是第三方包,后者是Qt官方做的,不過三者都兼容PyQt5就是了
3.1 QCustomPlot
??QCustomPlot目前在pypi上好像有好幾個版本
除此之外,如果直接運行pip install QCustomPlot2
也是可以安裝的,而且用著感覺和QCustomPlot-PyQt5沒什么區(qū)別,所以也不知道啥有這么多的版本。
??不過這個包有一個最大的問題,那就是它對Python的支持不夠好。網(wǎng)上有很多關(guān)于這個包在C環(huán)境下的使用,但是Python環(huán)境下卻不支持代碼提示,安裝的包是一個編譯過的pyd文件。
??以下是一個例子
import sys
import math
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPen, QBrush, QColor
from PyQt5.QtWidgets import QApplication, QMainWindow
from QCustomPlot2 import QCustomPlot, QCP
#以上QCustomPlot2完全可以直接換成QCustomPlot-PyQt5
app = QApplication(sys.argv)
window = QMainWindow()
window.resize(800, 600)
customPlot = QCustomPlot()
window.setCentralWidget(customPlot)
graph0 = customPlot.addGraph()
graph0.setPen(QPen(Qt.blue))
graph0.setBrush(QBrush(QColor(0, 0, 255, 20)))
graph1 = customPlot.addGraph()
graph1.setPen(QPen(Qt.red))
x, y0, y1 = [], [], []
for i in range (251):
x.append(i)
y0.append(math.exp(-i/150.0)*math.cos(i/10.0)) # exponentially decaying cosine
y1.append(math.exp(-i/150.0)) # exponential envelope
graph0.setData(x, y0)
graph1.setData(x, y1) #除setData外,還有addData函數(shù),即添加一個點
customPlot.rescaleAxes()
customPlot.setInteraction(QCP.iRangeDrag)
customPlot.setInteraction(QCP.iRangeZoom)
customPlot.setInteraction(QCP.iSelectPlottables)
window.show()
sys.exit(app.exec_())
以下是在類中的使用參考:
def initPlot(self):
self.ui.widget
self.ui.widget.setInteractions(QCP.iRangeDrag | QCP.iRangeZoom | QCP.iSelectAxes | QCP.iSelectLegend | QCP.iSelectPlottables)
# self.ui.widget.axisRect().setRangeZoomAxes(, self.ui.widget.yAxis)
self.ui.widget.xAxis.setLabel("t")
self.ui.widget.yAxis.setLabel("accel")
self.ui.widget.legend.setVisible(True)
self.ui.widget.yAxis.setRange(-2,2)
self.ui.widget.axisRect().insetLayout().setInsetAlignment(0, Qt.AlignLeft|Qt.AlignTop)
self.ui.widget.addGraph()#添加第1條曲線
self.ui.widget.graph(0).setName("x")#曲線名稱
self.ui.widget.graph(0).setPen(QPen(Qt.red)) # line1 color red for second graph
self.ui.widget.addGraph()#添加第2條曲線
self.ui.widget.graph(1).setName("y")#曲線名稱
self.ui.widget.graph(1).setPen(QPen(Qt.blue)) # line1 color red for second graph
self.ui.widget.addGraph()#添加第3條曲線
self.ui.widget.graph(2).setName("z")#曲線名稱
self.ui.widget.graph(2).setPen(QPen(Qt.green)) # line1 color red for second graph
self.ui.widget.addGraph()#添加第4條曲線
self.ui.widget.graph(3).setName("norm")#曲線名稱
self.ui.widget.graph(3).setPen(QPen(Qt.cyan)) # line1 color red for second graph
self.key_init = QDateTime.currentDateTime().toMSecsSinceEpoch()/1000
def fresh(self, x=0, y=0, z=0, norm=0):
key = QDateTime.currentDateTime().toMSecsSinceEpoch()/1000 - self.key_init
self.ui.widget.graph(0).addData(key, x)
self.ui.widget.graph(1).addData(key, y)
self.ui.widget.graph(2).addData(key, z)
self.ui.widget.graph(3).addData(key, norm)
self.ui.widget.rescaleAxes()
# self.ui.widget.xAxis.setRange(self.x, 8, Qt.AlignRight)
self.ui.widget.replot()
3.2 QtChart
??使用前先安裝:pip install PyQtChart
,在使用這個包時,要注意其基本的邏輯。顯示的類為QChartView, 但是QChartView需要關(guān)聯(lián)一個QChart,而每個QChart可以包含一個或多個series,即一條或多條曲線,當(dāng)然series類型有很多,這個和曲線計算方式和想要繪制圖形的類型有關(guān)。看個例子。
import sys
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout
from PyQt5.QtChart import QLineSeries, QChart, QChartView
def create_chart():
# 創(chuàng)建折線圖的數(shù)據(jù)
series = QLineSeries()
series.append(0, 0)
series.append(1, 1)
series.append(2, 2)
series.append(3, 3)
chart = QChart()
chart.addSeries(series)
chart.setTitle('Chart Example') # 設(shè)置圖表標(biāo)題
chart.setAnimationOptions(QChart.SeriesAnimations) # 設(shè)置動畫效果
return chart
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle('QtChart Example')
chart_view = QChartView(create_chart())
chart_view.setRenderHint(QPainter.Antialiasing) # 設(shè)置渲染方式
self.setCentralWidget(chart_view)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
//2023.5.16
這個有一點需要注意的是,序列,坐標(biāo)系,圖表的建立要遵循一定的順序,具體可以參考這篇博客中的代碼。
3.3 QWT
??這個沒有用過,但是感覺還行,也有代碼提示,安裝方法:
# 一定要安裝這個包,否則無法使用
pip install pyqt5-tools
# 再安裝對應(yīng)的包
pip install PythonQwt
這里給一個pypi官網(wǎng)提供的例子:
from qtpy import QtWidgets as QW
import qwt
import numpy as np
app = QW.QApplication([])
x = np.linspace(-10, 10, 500)
plot = qwt.QwtPlot("Trigonometric functions")
plot.insertLegend(qwt.QwtLegend(), qwt.QwtPlot.BottomLegend)
qwt.QwtPlotCurve.make(x, np.cos(x), "Cosinus", plot, linecolor="red", antialiased=True)
qwt.QwtPlotCurve.make(x, np.sin(x), "Sinus", plot, linecolor="blue", antialiased=True)
plot.resize(600, 300)
plot.show()
app.exec_()
3.4 Qt Designer中如何使用
??在上面的前期教程當(dāng)中,有提到PyQt常用的開發(fā)方式,就是在Qt Designer中設(shè)計ui,然后轉(zhuǎn)換成py文件,再另寫一個py文件進行界面的顯示和處理。那這些曲線怎么在Qt Designer中設(shè)計呢?
??在需要顯示的位置放置一個Widget控件:
然后右鍵該控件,選擇“提升為”
文章來源:http://www.zghlxwxcb.cn/news/detail-528747.html
這里主要是填兩個空,即提升的類名稱和頭文件,由于Python當(dāng)中沒有頭文件,實際填的是模塊名。即保證結(jié)構(gòu)是from B import A
,其中A應(yīng)該是一個顯示的類,具體應(yīng)該填什么根據(jù)使用的包決定。比如如果使用的是QtChart,那么應(yīng)該是from PyQt5.QtChart import QChartView
文章來源地址http://www.zghlxwxcb.cn/news/detail-528747.html
參考鏈接
- PyQt5 QSerialPort子線程操作
- Python3+PyQt5+QtChart 實現(xiàn)簡單的實時更新曲線圖
- QChart的簡單使用
- Qwt、QChart、QCustomPlot使用
- PyQtChart
到了這里,關(guān)于【PyQt】PyQt5進階——串口上位機及實時數(shù)據(jù)顯示的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!