Search code examples
pythonuser-interfacepyqt4qthread

GUI is very sluggish using PyQt and Qthreads


I have a problem with keeping a GUI responsive using PyQt and Qthreads. What I do is spawn a worker Qthread from the GUI which is cpu heavy. The worker Qthread sends a signal containing a numerical value in every cycle. In the GUI the signal is connected to an update function which takes the numerical value and repaints the GUI. I use the standard Qt SIGNAL/SLOT mechanism.

This all seems in line with documentation I've found online regarding PyQt, GUIs and Qthreads. The problem is that the worker thread triggers the signal so frequent, that the GUI becomes very sluggish. A solution would be to have the worker thread trigger the signal less frequent, but I would like to get a fast update of the progress.

This all seems very standard stuff, and yet I can't find a proper solution. Possibly I need to change the design?

Any help would be appreciated.

Code:

import calculator as ca

class GUI(QMainWindow):

    def __init__(self, config):
        QMainWindow.__init__(self)
        self.w_thread = WorkerThread()
        self.connect(self.w_thread, SIGNAL("update(PyQt_PyObject)"), self.update_gui)

    def start_calc(self):
        self.w_thread.start()

    def update_gui(self, progress_value):
        self.progress_value = progress_value
        self.repaint()

    def paintEvent(self, event):
        paint = QPainter()
        paint.begin(self)
        paint.drawText(300, 300, "progress: " + str(self.progress_value))
        paint.end()


class WorkerThread(QThread):

    def __init__(self):
        QThread.__init__(self)

    def __del__(self):
        self.wait()

    def run(self):
        ca.run_calculations(self)



*************** calculator.py ***************

def run_calculations(thread=None):

    while current_cycle < total_cycles:
        do_calculations()
        if current_cycle % 100 == 0:
            thread.emit(SIGNAL("update(PyQt_PyObject)"), current_progress_value)
        qApp.processEvents()
        current_cycle += 1

Solution

  • Adding qApp.processEvents() in the main loop of the worker thread seems to solve the problem.