您需要使用QThread
和信号和插槽。QThread
继承自QObject
,它允许发出信号。
任务完成后,QThread 会发出一个finished()
信号
编辑
如果您像这样定义自定义线程:
class CustomThread(QtCore.QThread):
def __init__(self, target, slotOnFinished=None):
super(CustomThread, self).__init__()
self.target = target
if slotOnFinished:
self.finished.connect(slotOnFinished)
def run(self, *args, **kwargs):
self.target(*args, **kwargs)
您将能够:
class MyCustomWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MyCustomWidget, self).__init__(parent)
layout = QtGui.QVBoxLayout(self)
button = QtGui.QPushButton("Start", self)
layout.addWidget(button)
button.clicked.connect(self.onStart)
self.actionthread = CustomThread(target=self.longAction, self.onFinished)
def onFinished(self):
# Do Something
def longAction(self):
time.sleep(3)
def onStart(self):
self.actionthread.start()