参考链接:
http://110.41.41.135/pyqt5.php
原来:
import sys
from PyQt5.QtWidgets import QApplication
"""
程序启动入口
"""
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QPushButton, QRadioButton, QCheckBox, QLabel, QLineEdit, QPlainTextEdit
from PyQt5.uic import loadUi
"""
主窗口
"""
import time
class HelloWorld:
def __init__(self):
self.name = ''
def say(self):
time.sleep(10)
return 'Hello world, %s' % self.name
class HomeWindow:
def __init__(self):
# 加载ui文件创建ui对象
self.window = loadUi('ui/home.ui')
self.window: QWidget
# 显示该窗口对象
self.window.show()
# 按钮,事件监听 绑定方法
self.window.pushButton: QPushButton
self.window.pushButton.clicked.connect(self.pushButton_clicked)
def pushButton_clicked(self):
# 读取文本框内容
self.window.lineEdit: QLineEdit
s = self.window.lineEdit.text()
# 创建任务对象
helloWorld = HelloWorld()
helloWorld.name = s
# 输出
self.window.plainTextEdit: QPlainTextEdit
self.window.plainTextEdit.setPlainText(helloWorld.say())
if __name__ == "__main__":
app = QApplication([])
# 启动主窗口
w = HomeWindow()
sys.exit(app.exec_())
加入线程后:
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QPushButton, QRadioButton, QCheckBox, QLabel, QLineEdit, QPlainTextEdit
from PyQt5.uic import loadUi
from base_api.HelloWorldClass import HelloWorld
from PyQt5.QtCore import QThread
import time
"""
主窗口
"""
class HomeWindow:
def __init__(self):
# 加载ui文件创建ui对象
self.window = loadUi('ui/home.ui')
self.window: QWidget
# 显示该窗口对象
self.window.show()
# 按钮,事件监听 绑定方法
self.window.pushButton: QPushButton
self.window.pushButton.clicked.connect(self.pushButton_clicked)
# 线程对象
self.t = None
def pushButton_clicked(self):
# 读取文本框内容
# self.window.lineEdit: QLineEdit
# s = self.window.lineEdit.text()
# # 创建任务对象
# helloWorld = HelloWorld()
# helloWorld.name = s
# # 输出
# self.window.plainTextEdit: QPlainTextEdit
# self.window.plainTextEdit.setPlainText(helloWorld.say())
if self.t is None:
# 读取文本框内容
self.window.lineEdit: QLineEdit
s = self.window.lineEdit.text()
# 创建线程对象
self.t = ThreadTask()
self.t.name = s
self.t.output_access = self.output
# 开始线程
self.t.start()
def output(self, s: str):
self.window.plainTextEdit: QPlainTextEdit
self.window.plainTextEdit.setPlainText(s)
# self.window.plainTextEdit.appendPlainText(s)
# 线程结束
self.t = None
class ThreadTask(QThread):
def __init__(self):
super().__init__()
self.name = ''
self.output_access = None
def run(self):
if self.output_access is not None:
time.sleep(5)
self.output_access('Hello world, %s' % self.name)