【发布时间】:2019-03-30 07:49:21
【问题描述】:
这是一个基于 ekhumoro 的回答 here 和 here 的后续问题。
我想明白了,当使用pyqtSlot 正确定义插槽并分配给QThread(例如使用moveToThread())时,它将在此QThread 而不是调用线程中执行。此外,还需要与Qt.QueuedConnection 或Qt.AutoConnection 建立连接。
我编写了代码来测试这一点。我的目标是实现这样简单的目标:
带有按钮的 GUI,它开始一些耗时的工作并返回结果以显示在 GUI 中。
from PyQt5.Qt import *
class MainWindow(QMainWindow):
change_text = pyqtSignal(str)
def __init__(self):
super().__init__()
self.button = QPushButton('Push me!', self)
self.setCentralWidget(self.button)
print('main running in:', QThread.currentThread())
thread = Thread(change_text, self)
thread.start()
self.button.clicked.connect( thread.do_something_slow, Qt.QueuedConnection)
self.change_text.connect(self.display_changes, Qt.QueuedConnection)
@pyqtSlot(str)
def display_changes( self, text ):
self.button.setText(text)
class Thread(QThread):
def __init__(self, signal_to_emit, parent):
super().__init__(parent)
self.signal_to_emit = signal_to_emit
#self.moveToThread(self) #doesn't help
@pyqtSlot()
def do_something_slow( self ):
print('Slot doing stuff in:', QThread.currentThread())
import time
time.sleep(5)
self.signal_to_emit.emit('I did something')
if __name__ == '__main__':
app = QApplication([])
main = MainWindow()
main.show()
app.exec()
但是 .. gui 是阻塞的,并且插槽在主线程中被调用。
我错过了什么?必须是小东西(我希望)。
【问题讨论】:
标签: python pyqt pyqt5 qthread qt-signals