如何在PyQt5 GUI中添加线程?

时间:2017-06-18 18:57:54

标签: python multithreading qt pyqt5 qthread

所以我使用QT Designer创建了一个GUI。它工作得很好,但是在更复杂的调用中,它不会更新主窗口并锁定。我想在不断变化的后端信息中更新主窗口中的textEdit时运行我的CustomComplexFunction(),我希望它每2秒运行一次。以下代码似乎正确并且运行没有错误,但不更新textEdit。请注意我正在使用pushButton和textEdit导入从QT Designer设计的.ui文件,如果没有它,代码将无法运行。

Main.py

import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout, QMainWindow
from PyQt5.QtCore import QCoreApplication, QObject, QRunnable, QThread, QThreadPool, pyqtSignal, pyqtSlot
from PyQt5 import uic, QtGui

class Worker(QObject):
    newParams = pyqtSignal()

    @pyqtSlot()
    def paramUp(self):
        x=1
        for x in range(100):
            time.sleep(2)
            self.newParams.emit()
            print ("sent new params")
            x +=1

Ui_somewindow, _ = uic.loadUiType("mainwindow.ui") #the path to UI

class SomeWindow(QMainWindow, Ui_somewindow, QDialog):

    def __init__(self):

        QMainWindow.__init__(self)
        Ui_somewindow.__init__(self)
        self.setupUi(self)

        # Start custom functions
        self.params = {}
        self.pushButton.clicked.connect(self.complex) #NumEvent

    def complex(self):
        self.work = Worker() 
        self.thread = QThread()

        self.work.newParams.connect(self.changeTextEdit)
        self.work.moveToThread(self.thread)
        self.thread.start()

        self.CustomComplexFunction()

    def CustomComplexFunction(self):
        self.params['City'] = 'Test'

    def changeTextEdit(self):

        try: 
            City = self.params['City']
            self.textEdit_14.setPlainText(City) 
        except KeyError:
            City = None
if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = SomeWindow()
    window.show()
    sys.exit(app.exec_())

您可以看到Signals and Slots here的官方文档,而此SO post也非常有用,但似乎我正确构建了它。根据文档,发射器不关心是否使用信号。这可能是代码没有错误但也不起作用的原因。

有关如何使其发挥作用的任何想法?或至少某种方式来测试发射器和信号??

1 个答案:

答案 0 :(得分:2)

您忘记将线程连接到worker对象。

self.work = Worker()
self.thread = QThread()
self.thread.started.connect(self.worker.work) # <--new line, make sure work starts.
self.thread.start()

祝你好运:-)