一般情况单线程就可以很好的完成任务,但是对于GUI程序来说,单线程就不能完全满足需求。如果有耗时流程,在单线程的情况下,界面操作就会卡死,直到耗时操作完成,才会响应界面操作。为了解决这个问题,PyQt提供了两个异步操作的对象:QThread和QTimer。
QTimer
功能:定时器,固定时间触发消息
start(milliseconds)
启动定时器,单位是毫秒
stop()
停止定时器
QThread
功能:开辟一个线程,和主线程并行执行
start()
sleep(seconds)
线程休眠,单位秒
需求:分别使用QThread和QTimer
import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QWidget, QProgressBar
class MyWidget(QWidget):
def __init__(self):
super(MyWidget, self).__init__()
self.currentValue = 0
self.progessBar = QProgressBar(self)
self.progessBar.resize(200, 50)
self.progessBar.move(20, 20)
self.progessBar.setValue(self.currentValue)
# 定义一个定时器并启动定时器
self.time = QTimer()
self.time.timeout.connect(self.upgradeProgress)
self.time.start(200)
def upgradeProgress(self):
self.currentValue = (self.currentValue + 1) % 101
self.progessBar.setValue(self.currentValue)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWidget()
w.resize(500, 300)
w.move(300, 300)
w.setWindowTitle('Simple')
w.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, QProgressBar
class MyWorker(QThread):
timeout = pyqtSignal()
def __init__(self):
super(MyWorker, self).__init__()
def run(self):
while True:
self.timeout.emit()
self.sleep(1)
class MyWidget(QWidget):
def __init__(self):
super(MyWidget, self).__init__()
self.currentValue = 0
self.progessBar = QProgressBar(self)
self.progessBar.resize(200, 50)
self.progessBar.move(20, 20)
self.progessBar.setValue(self.currentValue)
self.worker = MyWorker()
self.worker.timeout.connect(self.upgradeProgress)
self.worker.start()
def upgradeProgress(self):
self.currentValue = (self.currentValue + 1) % 101
self.progessBar.setValue(self.currentValue)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWidget()
w.resize(500, 300)
w.move(300, 300)
w.setWindowTitle('Simple')
w.show()
sys.exit(app.exec_())