QThread在后台工作正常,但GUI是否冻结?

时间:2019-12-05 08:31:03

标签: python pyqt pyqt5

我有一个应用程序,并且可以在QThread中执行某些操作,该线程可以处理信号并可以执行某些操作,但是我的GUI在线程运行时冻结了,那不是我想要的,我不知道为什么QThread可以冻结我的窗口,我尝试了其他方法,但最终失败了,任何人都可以帮助我,谢谢。

代码如下:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from pubsub import pub
import time

class Worker(QObject):
    sig_hello = pyqtSignal(str)
    sig_test = pyqtSignal(object)
    def __init__(self):
        super().__init__()
        self.count = 0

    def run(self):
        start_time = time.time()
        while True:
            self.count += 1
            time.sleep(0.2)
            print('working do something')
            if time.time() - start_time > 1000:
                break
            if self.count%2 == 1:
                print('signal emited')
                self.sig_test.emit(time.time() )
                self.sig_hello.emit('Hell0')


class WindowA(QFrame):
    def __init__(self):
        super().__init__()

        self.thread = QThread()
        self.thread.start()
        self.thread.quit()
        self.worker = None

        self.start_button = QPushButton('测试', clicked=self.onUnitTest, parent=self)

    @pyqtSlot()
    def onUnitTest(self):
        if self.thread.isFinished() :
            #send windowA to windowB
            pub.sendMessage('TOPA', win=self)

class WindowB(QFrame):
    def __init__(self):
        super().__init__()
        pub.subscribe(self.onUnitTest, topicName='TOPA')
        self.winA = None

    def onUnitTest(self, win):
        #recv windowA and start a thread
        self.winA = win
        self.winA.thread = QThread()
        self.winA.worker = Worker()

        self.winA.thread.started.connect(self.winA.worker.run)
        self.winA.worker.moveToThread(self.winA.thread)
        self.winA.worker.sig_test.connect(self.recv_test)
        self.winA.worker.sig_hello.connect(self.recv_hello)

        self.winA.thread.start()

    def recv_hello(self, ob):
        print('recv hello sig')

    def recv_test(self, ob):
        print('recv test sig')

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        winA = WindowA()
        winB = WindowB()

        layout = QVBoxLayout()
        layout.addWidget(winA)
        layout.addWidget(winB)
        self.setLayout(layout)
        self.resize(400, 300)

app = QApplication([])
win = MainWindow()
win.show()
app.exec()

结果被冻结:

  

1

0 个答案:

没有答案