我在使用 PyQt 和 Qthreads 保持 GUI 响应时遇到问题。我所做的是从 GUI 中生成一个工作线程 Qthread,它的 CPU 很重。worker Qthread 在每个周期发送一个包含数值的信号。在 GUI 中,信号连接到更新函数,该函数获取数值并重新绘制 GUI。我使用标准的 Qt SIGNAL/SLOT 机制。
这一切似乎与我在网上找到的有关 PyQt、GUI 和 Qthreads 的文档一致。问题是工作线程如此频繁地触发信号,以至于 GUI 变得非常缓慢。一个解决方案是让工作线程不那么频繁地触发信号,但我想快速更新进度。
这一切看起来都很标准,但我找不到合适的解决方案。可能我需要更改设计?
任何帮助,将不胜感激。
代码:
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