在文本编辑框中每隔几秒添加一行文本,代码如下:
1 #!/usr/bin/python3 2 # -*- coding:utf-8 -*- 3 4 import sys 5 from PyQt5.QtWidgets import (QApplication, 6 QWidget, 7 QLineEdit, 8 QPushButton, 9 QTextEdit, 10 QGridLayout) 11 from PyQt5.QtCore import (Qt, 12 QThread, 13 pyqtSignal, 14 pyqtSlot) 15 16 17 class Window(QWidget): 18 def __init__(self, parent=None): 19 super(Window, self).__init__(parent, Qt.Widget) 20 21 self.resize(460, 460) 22 self.setWindowTitle("Thread Test") 23 24 self.lineEdit = QLineEdit(self) 25 self.lineEdit.setPlaceholderText("connect to...") 26 self.pushButton = QPushButton(">>", self) 27 self.pushButton.setFixedWidth(30) 28 self.stopButton = QPushButton("×", self) 29 self.stopButton.setFixedWidth(30) 30 self.textEdit = QTextEdit(self) 31 self.textEdit.setPlaceholderText("result...") 32 33 grid = QGridLayout() 34 grid.addWidget(self.lineEdit, 0, 0, 1, 3) 35 grid.addWidget(self.pushButton, 0, 3) 36 grid.addWidget(self.stopButton, 0, 4) 37 grid.addWidget(self.textEdit, 1, 0, 5, 5) 38 self.setLayout(grid) 39 40 self.show() 41 42 43 class Run(Window): 44 sig = pyqtSignal(str) 45 46 def __init__(self): 47 super().__init__() 48 49 self.my_thread = None 50 self.pushButton.clicked.connect(self.button) 51 self.stopButton.clicked.connect(self.stop_button) 52 53 def button(self): 54 self.textEdit.clear() 55 line_text = self.lineEdit.text() 56 # 创建线程 57 self.my_thread = MyThread() 58 # 将自定义信号sig连接到MyThread.on_source函数 59 self.sig.connect(self.my_thread.on_source) 60 # 向MyThread.on_source函数传递line_text 61 self.sig.emit(line_text) 62 # 直接调用MyThread.on_source()也可以,但还是建议使用信号传递,在灵活性和性能上更佳 63 # self.my_thread.on_source(line_text) 64 # 将自定义信号signal连接到information()槽函数 65 self.my_thread.signal.connect(self.information) 66 # 启动线程 67 self.my_thread.start() 68 self.pushButton.setEnabled(False) 69 70 @pyqtSlot(str) 71 def information(self, info): 72 # 向textEdit添加lineEdit的文本 73 self.textEdit.append(info) 74 75 def stop_button(self): 76 self.pushButton.setEnabled(True) 77 # 将MyThread.running设为False以停止线程 78 self.my_thread.running = False 79 80 81 class MyThread(QThread): 82 # 自定义型号,执行run()函数时,从相关线程发射此信号 83 signal = pyqtSignal(str) 84 85 def __init__(self): 86 super().__init__() 87 self.source_txt = None 88 self.running = True 89 90 # 当发生QThread: Destroyed while thread is still running错误时,添加QThread.wait() 91 # def __del__(self): 92 # self.wait() 93 94 def on_source(self, line_text): 95 self.source_txt = line_text 96 97 @pyqtSlot() 98 def run(self): 99 while self.running: 100 # 发出信号 101 self.signal.emit(self.source_txt) 102 # 线程休眠1秒 103 self.sleep(1) 104 105 106 if __name__ == "__main__": 107 app = QApplication(sys.argv) 108 win = Run() 109 sys.exit(app.exec_())
界面如图:
当线程开始运行时,每隔1秒传递一个self.source_txt。
点击pushButton时,使按钮不可用,并启动线程,在文本编辑框内不断插入lienEdit的内容。
点击stopButton时,停止线程。