PyQt5 QSerialPort子线程操作的实现
环境:
python3.6 pyqt5
只是简单的一个思路,请忽略脆弱的异常防护:
# -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import * from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo from PyQt5.QtCore import pyqtSignal, QThread, QObject, QTimer class SerialWork(QObject): def __init__(self): super().__init__() def init(self): self.com = QSerialPort() self.com.setPortName('COM7') self.com.setBaudRate(115200) if self.com.open(QSerialPort.ReadWrite) == False: return self.readtimer = QTimer() self.readtimer.timeout.connect(self.readData) self.readtimer.start(100) def readData(self): revData = self.com.readAll() revData = bytes(revData) print('%d read' % len(revData)) class PyQt_Serial(QWidget): def __init__(self): super().__init__() self.serialthread = QThread() self.serialwork = SerialWork() self.serialwork.moveToThread(self.serialthread) self.serialthread.started.connect(self.serialwork.init) self.serialthread.start() if __name__ == '__main__': app = QApplication(sys.argv) win = PyQt_Serial() win.show() sys.exit(app.exec_())
需要注意的地方:
1、对QSerialPort的读写操作需要在同一个线程,不能跨线程操作
2、serialwork内不能有死循环,原因可能是死循环阻塞了串口接收事件的传递,导致readall函数一直读不到数据。如果非要加入死循环,在循环内加入QApplication.processEvents()可以读到串口数据
3、通过这次子线程操作QSerialPort的例程大致了解了两种QThread使用的阵营:run和moveToThread,哈哈
相关推荐
arctan0 2020-10-14
hackerlpy 2020-09-25
大唐帝国前营 2020-08-18
yuanlu 2020-08-17
chunjiekid 2020-08-16
cuiweisaidelike 2020-08-02
comeonxueRong 2020-08-02
zzqLivecn 2020-07-09
yunfeitian 2020-07-05
hell0kitty 2020-07-04
TreasureZ 2020-06-25
阿亮 2020-06-21
瓜牛呱呱 2020-11-12
starinshy 2020-11-10
farewellpoem 2020-11-09
Charlesbases 2020-10-23
温攀峰 2020-09-16
天空一样的蔚蓝 2020-09-04
ericxieforever 2020-09-03