暂停线程而不冻结gui

问题描述 投票:0回答:1

所以我有一个运行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()

我希望some_other_method()t1线程完成后运行。我不能使用。join(),因为它会冻结UI,并且我不能在threadFile中包含some_other_method(),因为some_other_method()是我的实例方法main.py并将类导入到我的threadFile中将产生循环导入。我希望我的问题很清楚。

python pyqt
1个回答
0
投票

然后创建一个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_())
© www.soinside.com 2019 - 2024. All rights reserved.