所以我创建了一个使用QT Designer的GUI。它工作得很好,但在更复杂的调用中它不会更新主窗口并锁定。我想在不断变化的后端信息更新主窗口中的textEdit时运行我的CustomComplexFunction()
,并且我希望它每2秒运行一次。下面的代码看起来是正确的,并且运行没有错误,但不会更新textEdit。请注意我正在使用pushButton和textEdit导入一个由QT Designer设计的.ui文件,如果没有它,代码将无法运行。如何添加线程到PyQt5 GUI?
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也非常有帮助,但好像我正确建立它。根据文档,发射器不关心信号是否被使用。这可能是代码没有错误但不起作用的原因。
关于如何使其工作的任何想法?或者至少有一些方法来测试发射器和信号?
祝你不是总设置相同的文字,即'self.params [ '市']'?每两秒调用一次'changeTextEdit'? – m7913d
也许,但它无法运行,所以我还没有注意到。 – RknRobin
实际上不是,'CustomComplexFunction()'在每隔7秒左右改变'self.params ['CIty']'的背景。为简单起见,我将其留作示例,但'self.params'是我想要从主窗口监控的。 – RknRobin