如何在非主线程QObject中开始工作

时间:2017-01-11 22:27:25

标签: python pyqt pyqt5 signals-slots qthread

基于网络上的Qt文档和其他示例,我认为以下使用QThread.started信号的程序将启动 非主线程中的工作程序 即可。但事实并非如此,而是从线程调用每个work广告位:

import time
import sys

from PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QApplication, QPushButton, QTextEdit, QVBoxLayout, QWidget


def trap_exc_during_debug(*args):
    # when app exits, put breakpoint in next line when run in debugger, and analyse args
    pass


sys.excepthook = trap_exc_during_debug


class Checker(QObject):
    sig_step = pyqtSignal(int, str)
    sig_done = pyqtSignal(int)

    def __init__(self, id: int):
        super().__init__()
        self.__id = id

    @pyqtSlot()
    def work(self):
        thread_name = QThread.currentThread().objectName()
        thread_id = int(QThread.currentThreadId())
        print('running work #{} from thread "{}" (#{})'.format(self.__id, thread_name, thread_id))

        time.sleep(2)
        self.sig_step.emit(self.__id, 'step 1')
        time.sleep(2)
        self.sig_step.emit(self.__id, 'step 2')
        time.sleep(2)
        self.sig_done.emit(self.__id)


class MyWidget(QWidget):
    NUM_THREADS = 3

    sig_start = pyqtSignal()

    def __init__(self):
        super().__init__()

        self.setWindowTitle("Thread Example")
        form_layout = QVBoxLayout()
        self.setLayout(form_layout)
        self.resize(200, 200)

        self.push_button = QPushButton()
        self.push_button.clicked.connect(self.start_threads)
        self.push_button.setText("Start {} threads".format(self.NUM_THREADS))
        form_layout.addWidget(self.push_button)

        self.log = QTextEdit()
        form_layout.addWidget(self.log)
        # self.log.setMaximumSize(QSize(200, 80))

        self.text_edit = QTextEdit()
        form_layout.addWidget(self.text_edit)
        # self.text_edit.setMaximumSize(QSize(200, 60))

        QThread.currentThread().setObjectName('main')
        self.__threads_done = None
        self.__threads = None

    def start_threads(self):
        self.log.append('starting {} threads'.format(self.NUM_THREADS))
        self.push_button.setDisabled(True)

        self.__threads_done = 0
        self.__threads = []
        for idx in range(self.NUM_THREADS):
            checker = Checker(idx)
            thread = QThread()
            thread.setObjectName('thread_' + str(idx))
            self.__threads.append((thread, checker))  # need to store checker too otherwise will be gc'd
            checker.moveToThread(thread)
            checker.sig_step.connect(self.on_thread_step)
            checker.sig_done.connect(self.on_thread_done)

            # self.sig_start.connect(checker.work)  # method 1 works: each work() is in non-main thread
            thread.started.connect(checker.work)  # method 2 doesn't work: each work() is in main thread
            thread.start()

        self.sig_start.emit()  # this is only useful in method 1

    @pyqtSlot(int, str)
    def on_thread_step(self, thread_id, data):
        self.log.append('thread #{}: {}'.format(thread_id, data))
        self.text_edit.append('{}: {}'.format(thread_id, data))

    @pyqtSlot(int)
    def on_thread_done(self, thread_id):
        self.log.append('thread #{} done'.format(thread_id))
        self.text_edit.append('-- Thread {} DONE'.format(thread_id))
        self.__threads_done += 1
        if self.__threads_done == self.NUM_THREADS:
            self.log.append('No more threads')
            self.push_button.setEnabled(True)


if __name__ == "__main__":
    app = QApplication([])

    form = MyWidget()
    form.show()

    sys.exit(app.exec_())

如果我使用自定义信号,它可以正常工作。要看到这一点,请注释"方法2"排除"方法1"行并重复运行。

在不必创建自定义信号的情况下启动工作人员肯定会更好,有没有办法做到这一点(同时坚持在工人身上调用moveToThread的设计)?

注意:QThread.started信号的文档没有多大帮助:

  

此信号在开始执行时从关联的线程发出

对我来说,这意味着started将在非主线程中发出,这样它连接的work槽将在非主线程中被调用,但这显然是不是这样的。即使我的解释不正确并且信号实际上是在主线程中发出的,对于两种方法默认Qt.AutoConnection,连接类型到{{1}上的一个插槽}移动到另一个线程,因此QObject信号应该异步传输(即通过每个检查器的QThread事件循环),显然不是这种情况。

1 个答案:

答案 0 :(得分:1)

我向jetbrains发布了支持请求,他们立即回答:

  

这是为了更好的调试而故意制作的。你可以取消选中   设置设置|构建,执行,部署| Python调试器>   PyQt兼容,并将按预期启动工作人员。

惊人!