如何使用pyqtgraph和QSerialPort创建实时图?

How to use pyqtgraph and QSerialPort to create a real-time graph?

总的来说,我对 Qt 和 python 还是有点陌生​​,所以我想知道是否可以为我正在从事的项目提供一些帮助。我想用 pyqtgraph 创建一个实时图形,绘制它使用 QSerialPort 通过 RS232 连接接收的数据。理论上,用户应该点击开始,发出来自 RS232 连接单元的数据流信号,当用户点击停止时,数据流将停止。下面的代码打开和关闭端口;但是,数据未绘制在图表上。提前致谢!


class Graph(QtGui.QWidget):
    def __init__ (self):                    
        super(Graph, self).__init__()      
        self.initializeSpace()
        
    def initializeSpace(self):
        # Create basic buttons next to graph
        self.start = QtGui.QPushButton(
            text = "Start",
            clicked = self.send)
        self.stop = QtGui.QPushButton(
            text = "Stop",
            clicked = self.stop)
         
        # Create plot
        self.graph = pg.PlotWidget()

        # Add grid
        self.graph.showGrid(x = True, y = True)

        # Set X-axis and Y-axis range
        self.graph.setXRange(0, 10)
        self.graph.setYRange(0, 200)

        # Create Layout
        self.layout = QtGui.QGridLayout()
       
        # Add widgets to layout
        self.layout.addWidget(self.start, 0, 0)
        self.layout.addWidget(self.stop, 1, 0)
        self.layout.addWidget(self.graph, 0, 1, 3, 1)

        # Set layout
        self.setLayout(self.layout)

        # Define himmelstein serial
        self.serial = QtSerialPort.QSerialPort(
            'COM4',
            baudRate = QtSerialPort.QSerialPort.Baud9600,     
            dataBits = QtSerialPort.QSerialPort.Data8,
            parity = QtSerialPort.QSerialPort.NoParity,
            stopBits = QtSerialPort.QSerialPort.OneStop, 
            flowControl = QtSerialPort.QSerialPort.NoFlowControl,
            readyRead = self.receive
            )

    @QtCore.pyqtSlot()
    def receive(self):
        while self.serial.canReadLine():
            data = self.serial.readLine().data().decode()
            data = data.strip('\r\n')
            torque = data[0]
            speed = data[1]
            self.graph.plot(x = torque, y = speed)
    
    # Send command and receive data
    @QtCore.pyqtSlot()
    def send(self):
        self.serial.open(QIODevice.ReadWrite)
        print("Port is open!")
        self.serial.write(b'ACD0\r\n')
        self.receive()

    def stop(self):
        if self.serial.isOpen():
            self.serial.close()
        print("Port closed!")

不,这是做不到的。目前甚至 Qt 还没有将 QSerialPort 模块包含到 Qt6 中,正如 this post 指出的那样:

For Qt 6.2 we are planning to provide the following additional libraries:

  • Qt Bluetooth
  • Qt Data Visualization
  • Qt Lottie Animation
  • Qt Multimedia
  • Qt NFC
  • Qt Positioning
  • Qt Quick Dialogs: Folder, Message Box
  • Qt Remote Objects
  • Qt Sensors
  • Qt SerialBus
  • Qt SerialPort
  • Qt WebChannel
  • Qt WebEngine
  • Qt WebSockets
  • Qt WebView

(强调我的)

目前只有Qt 6.1.2可用,PyQt6 6.1.1使用Qt 6.1.1