我想在我的主程序中调用一个方法ExecuteM
,其中在while
中循环Qt界面中的文本(调用result
),使用 Qt 创建者完成的将在每次迭代中更新。
class Machine():
def __init__(self, result):
self.result=result
def ExecuteM(self, Var1, Var2):
while Var1 != 'stop':
Var2 = Var2 + 3
self.result.setText(newResult())
sleep(0.5)
然后在我的主脚本中:
def main(self):
self.TM=Machine(self.result)
self.TM.ExecuteM(var1, var2)
但它不起作用,文本不会在每次迭代时更新,为什么?
最佳答案
如果在主线程中执行 while 循环,它将阻塞 gui。所有事件都将排队,直到 while 循环终止并且控制权可以返回到事件循环。因此,您要么必须将阻塞的 while 循环移至单独的线程中,要么定期强制事件循环处理待处理的事件。在您的示例中,应该可以像这样实现后者:
def ExecuteM(self, Var1, Var2):
while Var1 != 'stop':
Var2 = Var2 + 3
self.result.setText(newResult())
QApplication.processEvents()
sleep(0.5)
但这只是一个短期解决方案。 use a worker thread and send a custom signal back to the main thread 可能会更好.
关于python - 通过不在主脚本中的方法更新 Qt 界面中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091588/