gpt4 book ai didi

multithreading - 循环时更新PyQt4 GUI

转载 作者:行者123 更新时间:2023-12-03 13:04:39 27 4
gpt4 key购买 nike

我想在我的GUI中显示计算进度。为此,我希望每次进行计算时都更新我的PyQt4标签。我知道我应该使用线程来执行此操作,但这是行不通的。没有任何变化,并且while循环完成后,标签将更新为“100%”。即使线程正在工作,该值仍然不会平滑更新。我的代码中有注释,说明什么是什么。请帮我 :)

from PyQt4 import QtGui, QtCore
import time

class MyThread(QtCore.QThread):
trigger = QtCore.pyqtSignal(int)
def __init__(self, progress, parent=None):
super(MyThread, self).__init__(parent)
self.progress = progress #progress is a PyQt4 label object

def update_progress(self, value):
self.progress.setText(QtGui.QApplication.translate("Dialog", "Progress: %s " % value, None))
print "I was called", value
print self.progress #prints <PyQt4.QtGui.QLabel object at 0x0000000008151708>
#as you can see the object is passed all right
def run(self, value):
self.trigger.emit(value)

class Calculus:
def __init__(self):
print "object created"

@staticmethod
def euler(b,h,progress):
#progress is a PyQt4 label object, b and h are some integers
actions_done = 0
actions_number = b / h

thread = MyThread(progress)#create a thread
thread.trigger.connect(thread.update_progress)#connect it with a update function
thread.start()#start the thread


while t <= b:
actions_done+=1
progress_value = (actions_done/actions_number)*100

thread.run(progress_value)#emit signal?
t += h

thread.terminate()

@EDIT,这是我的解决方案,但存在内存泄漏问题
from PyQt4 import QtGui

class Calculus:
def __init__(self):
print "object created"

@staticmethod
def update_progress(self,value,ui_object):
ui_object.setText(QtGui.QApplication.translate("Dialog", "Progress: %s %%" % value, None))

#MEMORY LEAK WHEN UPDATING TOO MUCH (H=0.0001 AND B=1000)
QtGui.QApplication.processEvents() #update gui for pyqt



@staticmethod
def euler(b,h,progress):
actions_done = 0
actions_number = b * (1./h) #t = t+h. When h = 0.01 we need to perform t=t+h 100(1/h) times to get 1.
#when t varies from 0 to b, then we need to multiply this 1 * b(end time)
#so we get b * (1/h) as a number of actions to perform

scale = actions_number * 0.01

while t <= b:
actions_done+=1
progress_value = (actions_done/actions_number)*100

if (actions_done % scale == 0):
Calculus.update_progress(None,progress_value, progress)

t += h

最佳答案

以您自己的方式调用thread.run()并不会像您认为的那样进行。当前,它只是在主线程中执行thread.run()方法。

调用thread.start()会启动线程,并自动调用thread.run()方法。这样,您需要在thread.run()方法的内的while循环

这是因为您希望将完整的控制权传递给线程,并完成euler方法,以便可以将控制权返回到GUI事件循环(以便它可以处理重绘,以及更新进度条的方法)。 。您不应该尝试从主线程管理线程的执行。

关于multithreading - 循环时更新PyQt4 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30156762/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com