Sardor Abdirayimov
Sardor Abdirayimov

Reputation: 109

QThread msleep() vs. QTimer in PyQt5: Key Differences, Best Practices, and Use Cases

I am working on a PyQt5 application where I need to perform periodic tasks. I've come across two primary approaches:

The PyQt5 documentation recommends using QTimer for periodic tasks over blocking approaches like time.sleep() or QThread.msleep(). However, I am unsure if this is always the best option, especially when working inside a QThread.

Desired Outcome:

I want a scalable, thread-safe solution for periodic tasks in PyQt5. I’d like to understand:

Sample task: Periodically emit the camera output:

class MsleepWorker(QThread):
    frame_ready = pyqtSignal(QImage)

    def __init__(self, source=0):
        super().__init__()
        self.capture = cv2.VideoCapture(source)
        self.running = True

    def run(self):
        while self.running:
            ret, frame = self.capture.read()
            if ret:
                rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                h, w, ch = rgb_image.shape
                bytes_per_line = ch * w
                qt_image = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
                self.frame_ready.emit(qt_image)
            self.msleep(33)

    def stop(self):
        self.running = False
        self.quit()
        self.wait()
        self.capture.release()


class QTimerWorker(QThread):
    frame_ready = pyqtSignal(QImage)

    def __init__(self, source=0):
        super().__init__()
        self.capture = cv2.VideoCapture(source)

    def start(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.read_frame)
        self.timer.start(33)

    def stop(self):
        self.timer.stop()
        self.capture.release()

    def read_frame(self):
        ret, frame = self.capture.read()
        if ret:
            rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            h, w, ch = rgb_image.shape
            bytes_per_line = ch * w
            qt_image = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
            self.frame_ready.emit(qt_image)

Upvotes: 1

Views: 43

Answers (0)

Related Questions