【PyQt5 学习记录】004:简单QThread笔记

在文本编辑框中每隔几秒添加一行文本,代码如下:

 #!/usr/bin/python3
# -*- coding:utf-8 -*- import sys
from PyQt5.QtWidgets import (QApplication,
QWidget,
QLineEdit,
QPushButton,
QTextEdit,
QGridLayout)
from PyQt5.QtCore import (Qt,
QThread,
pyqtSignal,
pyqtSlot) class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent, Qt.Widget) self.resize(460, 460)
self.setWindowTitle("Thread Test") self.lineEdit = QLineEdit(self)
self.lineEdit.setPlaceholderText("connect to...")
self.pushButton = QPushButton(">>", self)
self.pushButton.setFixedWidth(30)
self.stopButton = QPushButton("×", self)
self.stopButton.setFixedWidth(30)
self.textEdit = QTextEdit(self)
self.textEdit.setPlaceholderText("result...") grid = QGridLayout()
grid.addWidget(self.lineEdit, 0, 0, 1, 3)
grid.addWidget(self.pushButton, 0, 3)
grid.addWidget(self.stopButton, 0, 4)
grid.addWidget(self.textEdit, 1, 0, 5, 5)
self.setLayout(grid) self.show() class Run(Window):
sig = pyqtSignal(str) def __init__(self):
super().__init__() self.my_thread = None
self.pushButton.clicked.connect(self.button)
self.stopButton.clicked.connect(self.stop_button) def button(self):
self.textEdit.clear()
line_text = self.lineEdit.text()
# 创建线程
self.my_thread = MyThread()
# 将自定义信号sig连接到MyThread.on_source函数
self.sig.connect(self.my_thread.on_source)
# 向MyThread.on_source函数传递line_text
self.sig.emit(line_text)
# 直接调用MyThread.on_source()也可以,但还是建议使用信号传递,在灵活性和性能上更佳
# self.my_thread.on_source(line_text)
# 将自定义信号signal连接到information()槽函数
self.my_thread.signal.connect(self.information)
# 启动线程
self.my_thread.start()
self.pushButton.setEnabled(False) @pyqtSlot(str)
def information(self, info):
# 向textEdit添加lineEdit的文本
self.textEdit.append(info) def stop_button(self):
self.pushButton.setEnabled(True)
# 将MyThread.running设为False以停止线程
self.my_thread.running = False class MyThread(QThread):
# 自定义型号,执行run()函数时,从相关线程发射此信号
signal = pyqtSignal(str) def __init__(self):
super().__init__()
self.source_txt = None
self.running = True # 当发生QThread: Destroyed while thread is still running错误时,添加QThread.wait()
# def __del__(self):
# self.wait() def on_source(self, line_text):
self.source_txt = line_text @pyqtSlot()
def run(self):
while self.running:
# 发出信号
self.signal.emit(self.source_txt)
# 线程休眠1秒
self.sleep(1) if __name__ == "__main__":
app = QApplication(sys.argv)
win = Run()
sys.exit(app.exec_())

界面如图:

【PyQt5 学习记录】004:简单QThread笔记

当线程开始运行时,每隔1秒传递一个self.source_txt。

点击pushButton时,使按钮不可用,并启动线程,在文本编辑框内不断插入lienEdit的内容。

点击stopButton时,停止线程。

【PyQt5 学习记录】004:简单QThread笔记

上一篇:Linux 第05天


下一篇:命令行发送SMTP协议邮件(163邮箱)