从PyQt GUI连接到串行

从PyQt GUI连接到串行,第1张

从PyQt GUI连接到串行

与其使用pySerial +线程,不如使用

QSerialPort
它与Qt事件循环一起使用:

from PyQt5 import QtCore, QtWidgets, QtSerialPortclass Widget(QtWidgets.QWidget):    def __init__(self, parent=None):        super(Widget, self).__init__(parent)        self.message_le = QtWidgets.QLineEdit()        self.send_btn = QtWidgets.QPushButton( text="Send", clicked=self.send        )        self.output_te = QtWidgets.QTextEdit(readonly=True)        self.button = QtWidgets.QPushButton( text="Connect",  checkable=True, toggled=self.on_toggled        )        lay = QtWidgets.QVBoxLayout(self)        hlay = QtWidgets.QHBoxLayout()        hlay.addWidget(self.message_le)        hlay.addWidget(self.send_btn)        lay.addLayout(hlay)        lay.addWidget(self.output_te)        lay.addWidget(self.button)        self.serial = QtSerialPort.QSerialPort( '/dev/tty.usbmodem14201', baudRate=QtSerialPort.QSerialPort.Baud9600, readyRead=self.receive        )    @QtCore.pyqtSlot()    def receive(self):        while self.serial.canReadLine(): text = self.serial.readLine().data().depre() text = text.rstrip('rn') self.output_te.append(text)    @QtCore.pyqtSlot()    def send(self):        self.serial.write(self.message_le.text().enpre())    @QtCore.pyqtSlot(bool)    def on_toggled(self, checked):        self.button.setText("Disconnect" if checked else "Connect")        if checked: if not self.serial.isOpen():     if not self.serial.open(QtCore.QIODevice.ReadWrite):         self.button.setChecked(False)        else: self.serial.close()if __name__ == '__main__':    import sys    app = QtWidgets.QApplication(sys.argv)    w = Widget()    w.show()    sys.exit(app.exec_())


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5644069.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存