使用PyQt5轻松实现多线程,用于更新QTextBrowser内容

问题描述 投票:0回答:1

我在网上找到了一些建议PyQt5小部件不是线程安全的东西。而其他Stackoverflow答案建议创建一个只适合他们的问题的类。我尝试在Python 3中使用_thread模块,它适用于除PyQt之外的所有内容。

app = QApplication([])
Ui_MainWindow, QtBaseClass = uic.loadUiType("UI/action_tab.ui") #specify the location of your .ui file


class MyApp(QMainWindow):
    def __init__(self):
        super(MyApp, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.threadPool = QThreadPool()
        self.ui.queryBox.returnPressed.connect(self.load_response)

    def start_loader(self):
        self.loading_animate = QMovie('IMAGES/GIFS/load_resp.gif')
        self.loading_animate.setScaledSize(QSize(400, 300))
        self.ui.loader.setMovie(self.loading_animate)
        self.loading_animate.setSpeed(200)
        self.ui.loader.show()
        self.loading_animate.start()

    def stop_loader(self):
        self.ui.loader.hide()
        self.loading_animate.stop()

    def get_response(self):
        plain_text, speech = get_Wresponse(self.ui.queryBox.displayText())
        self.stop_loader()
        self.ui.textDisplay.setText(plain_text)
        if speech == '':
            say("Here you GO!")
        else:
            say(speech)

    def load_response(self):
        self.start_loader()
        _thread.start_new_thread(self.get_response, ())
        #self.get_response()


if __name__ == '__main__':
    window = MyApp()
    window.setWindowFlags(Qt.FramelessWindowHint)
    window.show()
    sys.exit(app.exec())

上面的代码出错,

QObject: Cannot create children for a parent that is in a different thread. (Parent is QTextDocument(0x19fe090b8c0), parent's thread is QThread(0x19fde197fb0), current thread is QThread(0x19fe3a0a5f0)

你认为你能救我吗?请做!提前致谢!!

python python-3.x pyqt pyqt5
1个回答
0
投票

您不必从外部线程更新GUI。有几个选项,如信号,QMetaObject::invokeMethod(...),QEvent和QTimer::singleShot(0, ...)与pyqtSlot。

使用最后一种方法,解决方案如下:

from functools import partial
from PyQt5.QtCore import pyqtSlot

class MyApp(QMainWindow):
    # ...

    @pyqtSlot()
    def stop_loader(self):
        self.ui.loader.hide()
        self.loading_animate.stop()

    def get_response(self, text):
        plain_text, speech = get_Wresponse(text)
        QtCore.QTimer.singleShot(0, self.stop_loader)
        wrapper = partial(self.ui.textDisplay.setText, plain_text)
        QtCore.QTimer.singleShot(0, wrapper)
        if speech == '':
            say("Here you GO!")
        else:
            say(speech)

    def load_response(self):
        self.start_loader()
        text = self.ui.queryBox.displayText()
        _thread.start_new_thread(self.get_response, (text,))
© www.soinside.com 2019 - 2024. All rights reserved.