from PyQt5.Qt import *
import sys
class MyObject(QObject):
def timerEvent(self, evt):
print(evt, "1")
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("QObject 定时器的使用")
window.resize(500, 500)
obj = MyObject()
timer_id = obj.startTimer(1000)
# 指明定时器ID
obj.killTimer(timer_id)
window.show()
sys.exit(app.exec())
案例一:创建一个 QLabel,展示 10 秒倒计时
# 0. 导入需要的包和模块
from PyQt5.Qt import *
import sys
class MyObject(QObject):
def timerEvent(self, evt):
print(evt, "1")
class MyLabel(QLabel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setText("10")
self.move(100, 100)
self.setStyleSheet("font-size: 22px;")
def setSec(self, sec):
self.setText(str(sec))
def startMyTimer(self, ms):
self.timer_id = self.startTimer(ms)
def timerEvent(self, *args, **kwargs):
# 1. 获取当前的标签的内容
current_sec = int(self.text())
current_sec -= 1
self.setText(str(current_sec))
print(current_sec)
if current_sec == 0:
print("停止")
self.killTimer(self.timer_id)
# 1. 创建一个应用程序对象
app = QApplication(sys.argv)
# 2. 控件的操作
# 2.1 创建控件
window = QWidget()
# 2.2 设置控件
window.setWindowTitle("QObject定时器的使用")
window.resize(500, 500)
label = MyLabel(window)
# label.setSec(5)
# 设置初始秒值
label.startMyTimer(1000)
# 2.3 展示控件
window.show()
# 3. 应用程序的执行, 进入到消息循环
sys.exit(app.exec_())
网友评论