问题描述
关键是只有在有东西要读取时才具有读取功能,而不是使用没有特殊方法的pyserial。我想这可能会引发一个更大的问题,即是否可以在没有 GUI 类(从其他对象继承)的情况下使用信号和槽。我可以让串口写入,但不能读取
from PyQt5 import QtCore,QtSerialPort
serial_port = QtSerialPort.QSerialPort('COM3')
serial_port.open(QtCore.qiodevice.ReadWrite)
serial_port.write(bytes([255]))
def handle_ready_read():
while serial_port.canReadLine():
print(serial_port.readAll())
print('here')
serial_port.close()
serial_port.readyRead.connect(handle_ready_read)
即使在使用 pyserial 时读取了某些内容,也不会打印出任何内容。
解决方法
您不需要 GUI 即可使用 Qt。 Qt 中有一个专用的 GUI module,不依赖它的东西不需要 GUI。
但是,要使用槽和信号,您需要运行 Qt 的事件循环。常规方法是使用 QCoreApplication
。
app = QCoreApplication([])
# setup your serial port here
sys.exit(app.exec_())