简体   繁体   中英

QThread not work correctly and pyqt gui application freeze

I'm writing python gui application that process a image and send image color from serial port and show the results but unfortunately my gui freeze. i try using QApllication.processEvents and it is work but my program speed slow and speed is so important to me and every one second one iteration should be complete And then i use QThread and my application still freeze. Here is my code:

class Worker(QObject):

    progress = pyqtSignal(int)
    gui_update = pyqtSignal()

    def __init__(self, knot, lay, baft):
        super().__init__()
        self.knot = knot
        self.lay = lay
        self.baft = baft

    def run(self):

        while self.knot <= knotter_width:
            color_to_send = []
            for i in range(1, number_of_knotter + 1):
                color_to_send.append(self.baft["knotters"][i][self.lay][self.knot])

            self.progress.emit(self.knot)
            self.gui_update.emit() # for updating gui but not work

QThread setups:

self.thrd = QThread()
    self.worker = Worker(self.knot, self.lay, self.baft)
    self.worker.moveToThread(self.thrd)
    self.thrd.started.connect(self.worker.run)
    self.worker.progress.connect(self.progress)
    self.worker.gui_update.connect(self.knotters_status)
    self.worker.finish.connect(self.finished)
    self.worker.ex.connect(self.thrd.quit)
    self.worker.ex.connect(self.worker.deleteLater)
    self.thrd.finished.connect(self.thrd.deleteLater)

    self.thrd.start()

After three days of research i found that after setting up thread you need to call processEvents() just after creating thread object and in that situation it doesn't cause slowing down and every thing work perfectly. note: you should put the parameters in init function.

this is my final code:

class Thrd(QThread):

progress = pyqtSignal(int)
gui_update = pyqtSignal()
finish = pyqtSignal(bool)
ex = pyqtSignal()

def __init__(self, knot, lay, baft):
    super().__init__()
    self.knot = knot
    self.lay = lay
    self.baft = baft

def run(self):

    while condition:

        # some process

        self.progress.emit(self.knot)
        self.gui_update.emit()
        time.sleep(0.05) # give a little time to update gui

    self.finish.emit(True)
    self.ex.emit()

And setting up part:

self.thrd = Thrd(self.knot, self.lay, self.baft)
app.processEvents()
self.thrd.progress.connect(self.progress)
self.thrd.gui_update.connect(self.knotters_status)
self.thrd.finish.connect(self.finished)
self.thrd.ex.connect(self.thrd.quit)
self.thrd.finished.connect(self.thrd.deleteLater)
self.thrd.finished.connect(self.stop)
self.thrd.start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM