Pyqt-线程

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from MainWidget import *

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)
        self.thread = Worker()
        self.listFile = QListWidget()
        self.btnStart = QPushButton('开始')

        layout = QGridLayout(self)
        layout.addWidget(self.listFile, 0, 0, 1, 2)
        layout.addWidget(self.btnStart, 1, 1)

        self.btnStart.clicked.connect(self.slotStart)   # 启动线程
        self.thread.sinOut.connect(self.slotAdd)        # 将信号连接到slotAdd,信号由线程每隔2s发送一次

    def slotAdd(self, file_list):
        self.listFile.addItem(file_list)

    def slotStart(self):
        self.btnStart.setEnabled(False)
        self.thread.start()

# 新的线程:创建一个信号,该信号每隔2s发送一次
# 线程启动后会自动开始执行run()函数
class Worker(QThread):
    sinOut = pyqtSignal(str)    # 创建一个信号,信号必须在类创建时定义,不能在类创建后作为类的属性动态添加进来

    def __init__(self, parent=None):
        super(Worker, self).__init__(parent)
        self.working = True
        self.num = 0
    def __del__(self):
        self.working = False
        self.wait()
    def run(self):
        while self.working == True:
            file_str = 'File index{0}'.format(self.num)
            self.num += 1
            # 发射信号
            self.sinOut.emit(file_str)
            # 线程休眠2秒
            self.sleep(2)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    win = MainWidget()
    win.show()

    sys.exit(app.exec())

运行结果:点下开始按钮,每隔2s添加一个条目

Pyqt-线程

 

上一篇:题解 T121450 [Cnoi2020]明天后的幻想乡


下一篇:【pyqt】知识总结(1)