为什么我的PyQt线程不调用我的工作程序的函数?

时间:2019-11-15 02:42:41

标签: python pyqt qthread

我正在使用Python 3.6和PyQt5(特别是5.13.1)编写一个小型应用程序,以比较多个远程服务器上目录的文件校验和。我正在尝试为应用程序实现线程,但是当我启动线程时,我的工作程序中的函数无法执行。

我曾尝试搜索其他答案,但找不到任何可以帮助我解决这个问题的方法。我需要在线程启动时调用工作程序中的execute函数。

from PyQt5.QtWidgets import *
from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot, QObject


class CompareWorker(QObject):
    def __init__(self):
        super(CompareWorker, self).__init__()

    done = pyqtSignal()

    @pyqtSlot()
    def execute(self):
        print('Thread: ', int(QThread.currentThread().currentThreadId()))
        self.done.emit()


class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.button_compare = QPushButton('Compare')
        self.button_compare.clicked.connect(self.compare)

        self.setCentralWidget(self.button_compare)

    def compare(self):
        print('Main: ', int(QThread.currentThread().currentThreadId()))
        compare_worker = CompareWorker()
        compare_thread = QThread(self)
        compare_thread.started.connect(compare_worker.execute)
        compare_worker.done.connect(compare_thread.quit)
        compare_worker.done.connect(compare_worker.deleteLater)
        compare_worker.moveToThread(compare_thread)
        compare_thread.start()


if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

当前该应用程序正在运行,但是当我单击Compare按钮时,我得到的只是主线程的线程ID,如下所示:

Main:  10920

有人可以帮忙吗?

0 个答案:

没有答案