Pyqt5 qthread + signal not working + gui freeze

前端 未结 3 1215
半阙折子戏
半阙折子戏 2020-11-30 00:35

I am trying to make a mailbox checker with imap lib, it work pretty fine with python, queue and multithread without gui.

But when I try to put a gui, ev

3条回答
  •  孤街浪徒
    2020-11-30 01:19

    Sorry for late answer but it is a technique that can solve similar problems.

    The problem is clear. The GUI freezes because its thread has to do another job. An abstracted(from the PyQt point) solution is given below:

    1. Create a class inheriting from threading.Thread which will be the worker.
    2. Pass to the constructor a queue(queue.Queue) as a means of communication.
    3. You can start the worker thread from the GUI thread and pass messages by using the queue.
    4. To make the GUI thread read the messages, create a QTimer with interval of your choice and register a callback function. In the callback function read the queue.

    Example Code:

    class Worker(threading.Thread):
    
        def __init__(self, queue):
            super().init()
            self.queue = queue
    
        def run(self):
             # Your code that uses self.queue.put(object)
    
    class Gui:
    
        def __init__(self):
            self.timer = Qtimer()
            self.timer.setInterval(milliseconds)
            self.timer.timeout.connect(self.read_data)
    
    
        def start_worker(self):
            self.queue = queue.Queue()
    
            thr = Worker(self.queue)
    
            thr.start()
    
    
        def read_data(self):
            data = self.queue.get()
    

    self.timer.timeout.connect registers the callback function.

提交回复
热议问题