Pyqt5两个QThread通讯使用信号和插槽问题

时间:2018-07-21 11:45:03

标签: pyqt qthread

我正在尝试将pyqt qthread用于多线程程序。

在代码中,有两个不同的worker实例。我尝试使用信号和插槽进行数据共享。 但似乎信号被阻塞,直到qthread之一完成为止。

这是代码。

from PyQt5.QtCore import QCoreApplication,QThread, QObject, pyqtSignal, pyqtSlot
import time
import sys

class Worker(QObject):
    finished = pyqtSignal()
    intReady = pyqtSignal(int)

    @pyqtSlot()
    def work(self):  # A slot takes no params
        for i in range(1, 10):
            time.sleep(1)
            self.intReady.emit(i)

        self.finished.emit()


class Worker2(QObject):
    finished = pyqtSignal()
    intReady = pyqtSignal(int)

    @pyqtSlot()
    def work(self):  # A slot takes no params
        for i in range(1, 10):
            time.sleep(1)
            self.intReady.emit(i)

        self.finished.emit()

    @pyqtSlot(int)
    def revsignal(self, val):
        print("hello rev a signal"+str(val))

def updateLabel(val):
    print("updateLable "+str(val))

app = QCoreApplication(sys.argv)
# 1 - create Worker and Thread inside the Form
worker = Worker()  # no parent!
thread = QThread()  # no parent!

worker2 = Worker2()
thread2 = QThread()

worker.intReady.connect(updateLabel)
worker.intReady.connect(worker2.revsignal)

worker.moveToThread(thread)
worker.finished.connect(thread.quit)
thread.started.connect(worker.work)
# self.thread.finished.connect(app.exit)


worker2.moveToThread(thread2)
worker2.finished.connect(thread2.quit)
thread2.started.connect(worker2.work)

thread2.finished.connect(app.exit)



thread2.start()
print("after thread2 start")
thread.start()
print("after thread1 start.")



sys.exit(app.exec_())

输出在这里

after thread2 start
after thread1 start.
updateLable 1
updateLable 2
updateLable 3
updateLable 4
updateLable 5
updateLable 6
updateLable 7
updateLable 8
updateLable 9
hello rev a signal1
hello rev a signal2
hello rev a signal3
hello rev a signal4
hello rev a signal5
hello rev a signal6
hello rev a signal7
hello rev a signal8
hello rev a signal9

Process finished with exit code 0

我不知道为什么work1发出信号后worker2线程就不能接收信号。直到work1线程结束。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

第一件事是所有插槽都应该是从QObject继承的类的成员。所以做一个这样的课

class Manager(QObject):
    @pyqtSlot(int)
    def updateLabel(self, val):
        print("updateLable "+str(val))
manager = Manager()

接下来,根据文档here,还有一个附加参数可以传递给connect,以控制跨线程信号处理的行为。您需要更改三行。

from PyQt5.QtCore import QCoreApplication, QThread, QObject, pyqtSignal, pyqtSlot, Qt

获取Qt名称空间,以及

worker.intReady.connect(manager.updateLabel, type=Qt.DirectConnection)
worker.intReady.connect(worker2.revsignal, type=Qt.DirectConnection)

设置连接类型。