简体   繁体   中英

Is there in PyQt a signal that warns me on the presence of data in the input serial buffer?

I'm trying to create a GUI application with PyQt for a board that send me data packets with fixed lenght. The application reads these packets and shows some values contained in them. Leaving out the structure of the packets, my first attempt was to connect a timeout signal with my Update() function that update the values in the GUI:

timer = pg.QtCore.QTimer()
timer.timeout.connect(main.Update)
timer.start(10)

This solution emits a signal every 10 ms that activates the Update() routine. My question now is simple.

Since I don't like that, every some time, the application calls the Update() function, can I create a signal that warns on the presence of data in the input buffer? In this case the Update() function would be called only if necessary. Is it possible or the only solution is the polling?

I would just create a worker QObject in a separate thread that constantly checks the input buffer and emits a signal to the main thread when data is available

class Worker(QObject):

    data_ready = pyqtSignal(object)

    @pyqtSlot()
    def forever_read(self):
        while True:
            # Check input buffer
            data = something.read()
            if data:
                self.data_ready.emit(data)
            time.sleep(0.1)

In the main thread

class WindowOrObject(...)

    def __init__(self):
        ...
        self.worker = Worker(self)
        self.thread = QThread(self)
        self.worker.data_ready.connect(self.handle_data)
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.forever_read)
        self.thread.start()

    @pyqtSlot(object)
    def handle_data(self, data):
        # do something with data
        ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM