__author__ = "Fabian Dill" from queue import Queue, Empty from PySide2.QtCore import QTimer queue = Queue() _timer:QTimer def init(): global _timer """Run once to start queue handling from the mainthread. Preferably after the application is defined and before the mainloop, but should work at other times too. Only call this once.""" _timer = QTimer() _timer.timeout.connect(_handle_queue) _timer.setInterval(20) _timer.start(20) def mainthread(func): """Use as decorator around functions that can get called from threads, but should be run in mainthread. The function will immediately return without return value. Use callbacks or Signal emissions where necessary. Usage: @mainthread def my_func(param1): [run Qt functions] Later, simply call the decorated function from anywhere. It will be run with some delay, but all functions run this way keep their call order. """ def _wrapper(*args, **kwargs): queue.put(lambda:func(*args, **kwargs)) return _wrapper def _handle_queue(): while 1: try: task = queue.get(block=False) except Empty: return else: task() queue.task_done()