开发者

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()

    de开发者_开发百科f 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


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.

Because human reaction speed is much slower than the processing speed of a computer, this is the best, or at least the most likely to be simplest, solution. You can still get a "fast update of the progress" even if the GUI is only being repainted once every, say, 1/10th~1/30th of a second.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜