使用GUI我正在复制多个文件。对于每个文件,我开始一个线程。是否有一种方法可以让我得到一个信号或响应,告诉所有线程完成了他们的工作。我需要响应,因为根据所有线程完成时的响应,我想启用/禁用GUI上的几个按钮和复选框。
for file_name in _src_files:
if (os.path.exists(_full_file_name)):
t = Thread(target=file_util.copy_file, args=[_full_file_name, _str_destination_dir, 'update=1'])
t.start()
答案 0 :(得分:0)
您必须创建一个继承自QObject
并具有自定义信号的类,例如:
def copy_file(source, destination, message, log):
[...]
log.finished.emit()
class Logger(QObject):
finished = pyqtSignal()
self.l = Logger()
for file_name in _src_files:
if (os.path.exists(_full_file_name)):
t = Thread(target=file_util.copy_file, args=[_full_file_name, _str_destination_dir, 'update=1'], self.l)
t.start()
self.l.finished.connect(some_slot)
示例:
import time
from threading import Thread
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Logger(QObject):
finished = pyqtSignal(str)
def myfunc(i, log):
print("sleeping 5 sec from thread %d" % i)
time.sleep(5)
print("finished sleeping from thread %d" % i)
log.finished.emit("message %d" % i)
class Widget(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.l = Logger()
self.counter_threads = 0
for i in range(10):
t = Thread(target=myfunc, args=(i, self.l))
t.start()
self.counter_threads += 1
self.l.finished.connect(self.some_slot)
def some_slot(self, message):
print("some_slot: "+ message)
self.counter_threads -= 1
if self.counter_threads == 0:
print("finished all threads")
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())