Python PyQt将后端与GUI分开

时间:2018-05-25 12:36:44

标签: python multithreading pyqt

我希望我的Python后端不必等待我的PyQt GUI绘制(很多)东西。在PyQt中有没有比在下面的代码示例中更好/更正确的方法?是否有必要使用线程导入或PyQt有更好的方法吗?

import time
from threading import Thread

class Backend(Thread):
    def __init__(self):
        super().__init__()

    def run(self):
        for i in range(20):
            print("Backend heavy work")
            time.sleep(4)


class GUI(Thread):
    def __init__(self):
        super().__init__()

    def run(self):
        for i in range(20):
            print("GUI drawing stuff")
            time.sleep(0.5)

if __name__ == '__main__':
    thread_backend = Backend()
    thread_gui = GUI()

    thread_backend.start()
    thread_gui.start()

我尝试用Qtimer做这件事,但没有让它发挥作用。谢谢!

1 个答案:

答案 0 :(得分:0)

您无法从Qt循环外部更新UI。您可以做的是使用qt信号连接到为您完成工作的方法。作为一个例子

class GUI(QtCore.QObject): # must be a class that inherits QObject to use signals, I believe
    drawSignal = QtCore.pyqtSignal(int)
    def __init__(self):
        super().__init__()
        self.drawSignal.connect(self._drawStuff) # The underscore thing is a little hacky, but sort of pythonic I think, and makes the API clean.
        self.drawStuff = self.drawSignal.emit
    def _drawStuff(self, i):
        # do whatever you want to the gui here
        pass


class GUILoop(Thread):
    def __init__(self, gui):
        super().__init__()
        self.gui = gui
    def run(self):
        for i in range(20):
            self.gui.drawStuff(i)
            time.sleep(0.5)

if __name__ == '__main__':
    gui = GUI()
    thread_backend = Backend()
    thread_gui = GUILoop(gui)

    thread_backend.start()
    thread_gui.start()

看起来有点奇怪,但它很好地适应了Qt和Python的优势。将信号添加到已经QMainWindow的{​​{1}}类中可能也是有意义的。