基於Qt文檔和其他Web上的例子,我會認爲下面的程序使用QThread.started
信號,將啓動非工程線程。但是,這是不是這樣,而是每個work
插槽從主線程調用:如何在非主線程QObject中開始工作
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
,在插槽上QObject
移動到另一個線程,所以started
信號應該異步傳輸(即通過每個檢查器的QThread事件循環),但顯然不是這種情況。
對不起,但我不能重現這一點。兩種方法的輸出相同,並且所有線程都在主線程之外運行(這是在arch-linux上使用python 3.6.0,qt 5.7.1和pyqt 5.7)。 – ekhumoro
@ekhumoro感謝您的檢查。 Geez,這很奇怪,實際上只有當我通過PyCharm調試器(沒有斷點,順便說一句)運行時纔會發生。 Python的調試器(pdb)運行良好。我想我會用JetBrains打開一張票。 – Schollii