在pyqt5中我们通常需要在子线程中处理耗时操作如网络请求,在主线程中更新UI界面,下面是一个简单的例子,运行界面如下
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190322115258758.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2plZWttYXJ5,size_16,color_FFFFFF,t_70)
import sys
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QIcon, QCloseEvent
from PyQt5.QtWidgets import *
class MyThread(QThread):
send_singal = pyqtSignal(int)
def run(self):
for i in range(1, 5):
print("current id is: ", self.currentThreadId())
self.send_singal.emit(i)
QThread.sleep(1)
class Window(QWidget):
def __init__(self,*args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
self.resize(600, 400)
self.move(660,300)
self.setWindowTitle("标哥测试")
self.setUI()
self.intilogic()
def setUI(self):
self.layout = QVBoxLayout()
self.progress = QProgressBar()
self.progress.setRange(0, 100)
print(self.progress.width())
self.button = QPushButton("点击开始线程")
self.button.clicked.connect(self.start)
self.layout.addWidget(self.progress)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
def intilogic(self):
self.thread = MyThread(self)
self.thread.finished.connect(self.thread.deleteLater)
self.thread.send_singal.connect(self.change_value)
self.button.clicked.connect(self.start)
def change_value(self, value):
self.progress.setValue(value)
def start(self):
print('当前主线程ID: ', int(QThread.currentThreadId()))
try:
self.thread.start()
except:
print("子线程开启失败")
def closeEvent(self, a0: QCloseEvent):
print("关闭")
super(Window, self).closeEvent(a0)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())