Skip to main content

Python Qt thread updater to update GUI items using a separate thread.

Project description

Python Qt thread updater to update GUI items using a separate thread.

This library allows you to efficiently update Qt GUI elements from a separate thread. Qt GUI elements are not thread safe. Method calls like Label.setText do not work in a separate thread. This library solves that problem.

Utilities

The ThreadUpdater offers several utilities to help with updating a widget’s value.

  • call_latest - Call the given function with the most recent value in the main thread using the timer.

    • It is safe to call this many times with the same function.

    • If the given function is called multiple times it is only called once with the most recent value.

  • call_in_main - Call the given function in the main thread using the timer.

    • Every time you call this function the given function will be called in the main thread

    • If the given function is called multiple times it will be called every time in the main thread.

    • If this function is called too many times it could slow down the main event loop.

  • register_continuous - Register a function to be called every time the ThreadUpdater.update method is called.

    • The timeout variable (in seconds) indicates how often the registered functions will be called.

  • delay - Call a function after the given number of seconds has passed.

    • This will not be accurate. Accuracy can be improved by lowering the timeout to increase how often the timer runs.

Simple Thread Example

The example below tells the update to run lbl.setText in the main thread with the latest value.

import time
import threading
from qtpy import QtWidgets
from qt_thread_updater import get_updater

app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])

lbl = QtWidgets.QLabel("Latest Count: 0")
lbl.resize(300, 300)
lbl.show()

data = {'counter': 0}

def run(is_alive):
    is_alive.set()
    while is_alive.is_set():
        text = 'Latest Count: {}'.format(data['counter'])
        get_updater().call_latest(lbl.setText, text)
        data['counter'] += 1
        time.sleep(0.001)  # Not needed (still good to have some delay to release the thread)

alive = threading.Event()
th = threading.Thread(target=run, args=(alive,))
th.start()

app.exec_()
alive.clear()

Continuous Update Example

The example below continuously runs the update function every time ThreadUpdater.update() is called from the timer. This may be inefficient if there is no new data to update the label with.

import time
import threading
from qtpy import QtWidgets
from qt_thread_updater import get_updater

app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])

lbl = QtWidgets.QLabel("Continuous Count: 0")
lbl.resize(300, 300)
lbl.show()

data = {'counter': 0}

def update():
    """Update the label with the current value."""
    lbl.setText('Continuous Count: {}'.format(data['counter']))

get_updater().register_continuous(update)

def run(is_alive):
    is_alive.set()
    while is_alive.is_set():
        data['counter'] += 1
        # time.sleep(0.001)  # Not needed (still good to have some delay to release the thread)

alive = threading.Event()
th = threading.Thread(target=run, args=(alive,))
th.start()

app.exec_()
alive.clear()

Call In Main Example

The example below calls the append function every time. It may not be efficient.

import time
import threading
from qtpy import QtWidgets
from qt_thread_updater import get_updater

app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])

text_edit = QtWidgets.QTextEdit()
text_edit.resize(300, 300)
text_edit.setReadOnly(True)
text_edit.show()

data = {'counter': 0}

def run(is_alive):
    is_alive.set()
    while is_alive.is_set():
        text = 'Main Count: {}'.format(data['counter'])
        get_updater().call_in_main(text_edit.append, text)
        data['counter'] += 1
        time.sleep(0.01)  # Some delay/waiting is required

alive = threading.Event()
th = threading.Thread(target=run, args=(alive,))
th.start()

app.exec_()
alive.clear()

Delay Example

The example below calls the append function after X number of seconds has passed. The delay function will not be accurate, but guarantees that the function is called after X number of seconds. To increase accuracy give the ThreadUpdater a smaller timeout for it to run at a faster rate.

import time
import threading
from qtpy import QtWidgets
from qt_thread_updater import get_updater

app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])

text_edit = QtWidgets.QTextEdit()
text_edit.resize(300, 300)
text_edit.setReadOnly(True)
text_edit.show()

now = time.time()

def update_text(set_time):
    text_edit.append('Requested {:.04f} Updated {:.04f}'.format(set_time, time.time() - now))

# Lower the timeout so it runs at a faster rate.
get_updater().timeout = 0  # 0.0001  # Qt runs in milliseconds

get_updater().delay(0.5, update_text, 0.5)
get_updater().delay(1, update_text, 1)
get_updater().delay(1.5, update_text, 1.5)
get_updater().delay(2, update_text, 2)
get_updater().delay(2.5, update_text, 2.5)
get_updater().delay(3, update_text, 3)

app.exec_()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

qt_thread_updater-1.0.0.tar.gz (8.6 kB view details)

Uploaded Source

File details

Details for the file qt_thread_updater-1.0.0.tar.gz.

File metadata

  • Download URL: qt_thread_updater-1.0.0.tar.gz
  • Upload date:
  • Size: 8.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.21.0 setuptools/39.1.0 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.6.8

File hashes

Hashes for qt_thread_updater-1.0.0.tar.gz
Algorithm Hash digest
SHA256 f6186174dbc202b132fb365860106a9c4e450a8053e71ec73eff8c26120cc3f6
MD5 26a56e7f9fb58f7dd2899932e3f815ce
BLAKE2b-256 1f462fe76da6bf06b60da6a585f28abb8ce73053b56e83075fe706036ccc9b71

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page