1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Qt/PySide6: What is the best way to implement an infinite data fetching loop with a...

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024 às 15:52.

  1. Stack

    Stack Membro Participativo

    I am implementing a small multi-threaded GUI application with PySide6 to fetch data from a (USB-connected) sensor and to visualize the data with Qt. I.e., the use can start and stop the data fetching:

    [​IMG]

    When clicking the play button a worker object is created and moved to the QThread and the QThread is started. The internet is full of different approaches how to implement such an indefinite (data fetching loop). Here the two main approaches I've came across most often so far:

    • Approach 1 (indefinite but user-interruptible loop plus sleep()):

    class Worker(QObject):
    def __init__(self, user_stop_event: Event)
    self.user_stop_event = user_stop_event

    def run(self):
    while not user_stop_event.isSet():
    self.fetch_data()
    # Process received signals:
    Qtcore.QApplication.processEvents()
    # A sleep is important since in Python threads cannot run really in parallel (on multicore systems) and without sleep we would block the main (GUI) thread!
    QThread.sleep(50)

    def fetch_data(self):
    ...

    • Approach 2 (timer-based approach):

    class Worker(QObject):
    def __init__(self):
    timer = QTimer()
    timer.timeout.connect(self.fetch_data)
    timer.start(50)

    def fetch_data(self):
    ...


    Both alternatives use the same mechanism to start the thread:

    thread = QThread()
    worker = Worker()
    worker.moveToThread(thread )
    thread.started.connect(worker.run)
    ...


    What are the pros and cons of both approaches? What is the preferred implementation?

    Unfortunately, Qt's official Threading Basics website does not give clear advises here. Both are working on my side, but I am not quite sure which one shall be used our default implementation for subsequent projects.

    Continue reading...

Compartilhe esta Página