所以我有一个运行Qt GUI的程序。我不想发布程序代码,但是我显示的代码适用于我的代码。所以我的文件有了新的线程。
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("Starting Thread")
time.sleep(5)
some_method()
some_method2()
print("Closing Thread")
然后我得到了main.py
from threadFile import MyThread
t1 = MyThread()
MyThread.start()
self.some_other_method()
我希望在 t1 线程完成之后运行 some_other_method()。我不能使用 .join(),因为它会冻结UI,并且我不能在 threadFile 中包含 some_other_method(),因为 some_other_method ()是main.py中的实例方法,将类导入到 threadFile 中将产生循环导入。我希望我的问题很清楚。
答案 0 :(得分:1)
然后创建一个QObject,该QObject在任务完成执行时发出完成信号,并通过该信号调用所需的函数:
import threading
import time
from PyQt5 import QtCore, QtWidgets
class Signaller(QtCore.QObject):
started = QtCore.pyqtSignal()
finished = QtCore.pyqtSignal()
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.signaller = Signaller()
def run(self):
self.signaller.started.emit()
print("Starting Thread")
time.sleep(5)
print("Closing Thread")
self.signaller.finished.emit()
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.button = QtWidgets.QPushButton("Press me")
self.setCentralWidget(self.button)
self.button.clicked.connect(self.on_clicked)
@QtCore.pyqtSlot()
def on_clicked(self):
self.button.setEnabled(False)
t1 = MyThread()
t1.signaller.finished.connect(self.on_finished)
t1.start()
@QtCore.pyqtSlot()
def on_finished(self):
self.some_other_method()
self.button.setEnabled(True)
def some_other_method(self):
print("test")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())