Environment:
python3.6 PYQT5
Just a simple idea, please ignore the fragile exception protection:
#-*-Coding:utf-8-*-import sysfrom pyqt5.qtwidgets import *from pyqt5.qtserialport import Qserialport, QSerialPortInfof Rom pyqt5.qtcore import pyqtsignal, Qthread, Qobject, Qtimerclass serialwork (qobject): def __init__ (self): Super (). __init__ () def init (self): self.com = Qserialport () self.com.setPortName (' COM7 ') SELF.COM.S Etbaudrate (115200) if Self.com.open (qserialport.readwrite) = = False:return Self.readtimer = QT Imer () self.readtimer.timeout.connect (Self.readdata) Self.readtimer.start (+) def readdata (self): Revdata = Self.com.readAll () revdata = bytes (revdata) print ('%d read '% len (revdata)) class Pyqt_ser Ial (qwidget): def __init__ (self): Super (). __init__ () Self.serialthread = Qthread () self.serialwork = Serialwork () self.serialwork.moveToThread (self.serialthread) self.serialthread.started.connect (Self.seria Lwork.init) Self.serialthread.start () if __name__ = = ' __main__ ': app = Qapplication (sys.argv) win = Pyqt_serial () w In.show () Sys.exit (App.exec_ ())
Places to be aware of:
1. Read and write operations on Qserialport need to be on the same thread and cannot operate across threads
2, Serialwork can not have a dead cycle, the reason may be the dead loop blocked the serial port receive event transmission, resulting in readall function has been unable to read data. If you want to join the dead loop, add qapplication.processevents () in the loop to read the serial data
3, through this sub-threading operation Qserialport routines roughly understand the two qthread use of the camp: Run and movetothread, haha
PyQt5 Qserialport Sub-threading operations