Home > Software engineering >  How to schedule a function to run on the main UI thread in Qt for python?
How to schedule a function to run on the main UI thread in Qt for python?

Time:02-10

I am porting a python GTK application to use Qt for python(PySide2). It implements worker threads with python standard threading module and worker threads use Gdk.threads_add_idle() to interact with the main UI thread.

There are plenty of articles on QThread, but I couldn't find a simple way to do this with Qt.

I hacked and came to an ugly solution like the following. (For the core logic only, see the IdleRunner class and run_on_idle() function.)

import sys
import time
import threading
from PySide2.QtCore import *
from PySide2.QtWidgets import *

class IdleRunner(QObject):
    run = Signal(object, tuple, float)
    def __init__(self):
        super().__init__()
        self.run.connect(self.on_run)
    def on_run(self, func, args, delay):
        if delay: QTimer.singleShot(delay * 1000, lambda: func(*args))
        else: func(*args)
_idle_runner = IdleRunner()
def run_on_idle(func, *args, delay = 0):
    _idle_runner.run.emit(func, args, delay)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__(windowTitle = sys.argv[0])
        self.resize(400, 300)
        self.setAttribute(Qt.WA_DeleteOnClose, True)

        self.label = label = QLabel('aaa', alignment = Qt.AlignCenter)
        self.setCentralWidget(label)

        def thread_entry():
            time.sleep(1)
            run_on_idle(lambda: self.label.setText('bbb'))
            run_on_idle(self.close, delay = 1)
        self.thread = thread = threading.Thread(target = thread_entry)
        thread.start()
    def close(self):
        self.thread.join()
        super().close()

app = QApplication()
main_window = MainWindow()
main_window.show()
app.exec_()

I have two questions.

  1. What is the best solution to this?
  2. What are the possible problems of this solution? (Such as a memory leak).

CodePudding user response:

  •  Tags:  
  • Related