总的来说,我对 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!")