pythonpyqt将后端与GUI分开

pythonpyqt将后端与GUI分开,python,multithreading,pyqt,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)

我希望我的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做,但没有成功。谢谢大家!

不能从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类也可能是有意义的,因为它已经是QObject。

根据您在另一个线程中运行GUI的首字母缩写,这在Qt中是禁止的。