PyQt线程问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jeekmary/article/details/88737314

在pyqt5中我们通常需要在子线程中处理耗时操作如网络请求,在主线程中更新UI界面,下面是一个简单的例子,运行界面如下

在这里插入图片描述

# -*- coding: utf-8 -*-


import sys

from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QIcon, QCloseEvent
from PyQt5.QtWidgets import *

class MyThread(QThread):
    # 定义一个传输 int类型的信号
    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("标哥测试")
        # 设置logo
        # self.setWindowIcon(QIcon("logo.png"))
        # 初始化UI界面的控件
        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()))
        # 线程开启后再次点击是没有用的,也不会再次重新开始线程
        # 但是当线程运行完毕之后,由于上面调用了
        # self.thread.deleteLater 所以 在子线程运行完毕之后再次点击运行这段代码会报错,需要处理
        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_())

猜你喜欢

转载自blog.csdn.net/jeekmary/article/details/88737314