PyQt5 - Automate Serial module

て烟熏妆下的殇ゞ 提交于 2019-11-28 13:01:41

A basic rule in Qt is that the GUI should not be updated from a thread other than the main one, this is called the GUI thread. There are several options such as sending the data through signals to the main thread, or using a QRunnable with QThreadPool as shown below:

Code:

qtCreatorFile = "gui.ui" 
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
estudiantes = ['   ','    ','     ','    '] 

class SerialRunnable(QtCore.QRunnable):
    def __init__(self, w):
        QtCore.QRunnable.__init__(self)
        self.w = w
        self.ser = serial.Serial('COM9', baudrate=9600, timeout=1)

    def run(self):
        while True:
            dato = self.ser.readline().decode('ascii')
            if dato != "":
                QtCore.QMetaObject.invokeMethod(self.w, "setValues",
                                     QtCore.Qt.QueuedConnection,
                                     QtCore.Q_ARG(str, dato))
            QtCore.QThread.msleep(10)


class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.setupUi(self)
        runnable = SerialRunnable(self)
        QtCore.QThreadPool.globalInstance().start(runnable)

    @QtCore.pyqtSlot(str)
    def setValues(self, dato):
        estudiantes.insert(0,dato)
        estudiantes.pop()
        self.Box1.setText(estudiantes[0])
        self.Box2.setText(estudiantes[1])
        self.Box3.setText(estudiantes[2])
        self.Box4.setText(estudiantes[3])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!