python - 多个QThreads的PyQt确认完成
问题描述
我用 Qt Creator 和 Python 创建了一个 GUI 工具。在 GUI 中,用户将选择他/她想要生成的 shapefile 的类型。该脚本将选择存储在列表中。每种类型的 shapefile 的生成由单独的 QThreads 处理。每个 QThread 都会打印一些消息,例如“Processing AAA....”。然后“运行”按钮功能将执行以下操作:
if optionA in selection_list:
QThreadA.start()
if optionB in selection_list:
QThreadB.start()
if optionC in selection_list:
QThreadC.start()
现在我试图在所有 QThreads 完成时让 GUI 弹出一个窗口。我在这里https://riverbankcomputing.com/pipermail/pyqt/20 07-May/016026.html 发现QThread.wait() 与 thread.join() 的工作方式相同,我正在尝试使用它。
我不能做
if optionA in selection_list:
QThreadA.start()
if optionB in selection_list:
QThreadB.start()
if optionC in selection_list:
QThreadC.start()
QThreadA.wait()
QThreadB.wait()
QThreadC.wait()
print("All set")
因为有时并不是所有的 QThreads 都会运行。
但如果我这样做
if optionA in selection_list:
QThreadA.start()
if optionB in selection_list:
QThreadB.start()
if optionC in selection_list:
QThreadC.start()
if optionA in selection_list:
QThreadA.wait()
if optionB in selection_list:
QThreadB.wait()
if optionC in selection_list:
QThreadC.wait()
print("All set")
这不仅看起来很愚蠢,当我点击“运行”按钮时,我也会得到
"All set"
"Processing AAA..."
"Processing BBB..."
"Processing CCC..."
当显然一切都完成时,这些消息完全出现,而不是我希望看到的:
"Processing AAA..."
some time passed...
"Processing BBB..."
some more time passed...
"Processing CCC..."
some more time passed...
"All set"
这里发生的事情的顺序是什么?这基本上使消息毫无用处,因为用户只有在一切最终完成时才能看到它们。
可以使用一些关于如何重建功能的帮助。
编辑:根据@Nimish Bansal 的建议,我想出了这个:
dict = {optionA: QThreadA, optionB: QThreadB, optionC: QThreadC}
for option in selection_list:
dict[option].start()
为了避免以前愚蠢的“如果”,但我仍然没有找到一个有效的方法来结束所有线程,因为:
for options in selection_list:
dict[option].wait()
似乎不起作用,因为我猜 .wait() 会暂停 for 循环?
解决方案
def run_fun(a):
print("processing",a)
time.sleep(2)
import threading
A=threading.Thread(target=run_fun,args=('aaa',))
B=threading.Thread(target=run_fun,args=('bbb',))
C=threading.Thread(target=run_fun,args=('ccc',))
def join_threads(listi):
for j in listi:
j.join()
print("ALL set","open your gui here")
A.start()
B.start()
C.start()
threading.Thread(target=join_threads,args=([A,B,C],)).start()
输出
处理aaa
处理bbb
处理ccc
全部设置在这里打开你的 gui
推荐阅读
- r - 如何根据列名对包含 R 中多个列表的列表进行子集化,并合并到单个列表/数据框中?
- sql-server - SQL Server 是否计算后来丢弃的结果?
- android - Kotlin Companion Objection 未解决的引用
- python - Spark Mongo 连接器:在 MongoDB 连接中只插入一个属性
- java - 停止在 Android APK 中生成 javax.annotation 源文件
- vba - 使用 .Replace 撤消 ID
- javascript - 使用 data-attribute 和 click 函数将数据值推送到 div
- javascript - 多语言 PHP 链接
- d3.js - 在 ES6 中导入和使用 d3 及其子模块的正确方法是什么?
- mediawiki - 使用自定义路由教程创建自定义端点