separate functions from gui into process. lagging

前端 未结 1 710
野的像风
野的像风 2021-01-24 00:26

first i created the functional parts of my code and later decided to add a interface to it, so i have linked the interface and and the main function of the previous code as bell

相关标签:
1条回答
  • 2021-01-24 01:03

    Qt does not support multiprocessing so to remove complexity from the problem use threading. In this case Qt also indicates that the GUI should not be modified from another thread, instead of that I create a QObject and export it to the other thread, this QObject has a signal that transports the image.

    On the other hand when you do main(w) you are invoking the heavy task in the main process and that causes the GUI to freeze, instead you have to pass the name of the function, and the arguments of that function through of args:

    from PyQt5 import QtCore, QtGui, QtWidgets
    from PIL import Image
    from PIL.ImageQt import ImageQt
    from threading import Thread
    
    # ...
    
    class Signaller(QtCore.QObject):
        imageSignal = QtCore.pyqtSignal(Image.Image)
    
    
    class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            self.setupUi(self)
    
        def update_sheet2(self, Image):
            # ...
    
        @QtCore.pyqtSlot(Image.Image)
        def update_sheet1(self, Image):
            qim = ImageQt(Image)
            pix = QtGui.QPixmap.fromImage(qim)
            pix = pix.scaled(self.sheet1.width(), self.sheet1.height(), QtCore.Qt.KeepAspectRatio)
            self.sheet1.setPixmap(pix)
            self.sheet1.setAlignment(QtCore.Qt.AlignCenter)
    
    
    def run_ui():
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = MainWindow()
        w.show()
        signaller = Signaller()
        signaller.imageSignal.connect(w.update_sheet1)
        t = Thread(target=main, args=(signaller,), daemon=True)
        t.start()
        sys.exit(app.exec_())
    
    
    def main(signaller):
        for i in range(100000000):
            x=1
            y = x*x*x
        img = Image.open('XXX.png')
        signaller.imageSignal.emit(img)
    
    
    if __name__ == '__main__':
        run_ui()
    
    0 讨论(0)
提交回复
热议问题