PyQt-3

本文是PyQt3教程的第三部分,重点介绍了QTimer的使用。通过两个示例展示了如何创建定时器,其中Example 1展示了一个10秒后自动关闭的窗口,Example 2和3讲解了如何避免长时间运行槽函数导致的重叠调用问题,利用Try and Finally技巧确保计时器在函数执行完毕后再启动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PyQt Tutorial 3: QTimer

1. Example 1

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

app = QApplication(sys.argv)
label = QLabel("<font color=red size=128><b>Hello PyQT!</b></font>")
label.setWindowFlags(Qt.SplashScreen)
label.show()
QTimer.singleShot(10000, app.quit) # 设置10s后自动退出
app.exec_()

In this example, a windown which prints “Hello PyQT!” will appear in the screen, and then it will terminate in 10 seconds.

2. Example 2

# 初始化一个定时器
self.timer = QTimer(self)
# 在定时器计时结束时触发self.showNum
self.timer.timeout.connect(self.showNum)
# 每1000毫秒计时一次
self.timer.start(1000)

def showNum(self):
    count = count + 1
    print(count)

3. A trick to use QTimer with Try and Finally:

In the example above, self.showNum is called every 1 second, and because self.showNum only takes very little time to run, we don’t need to worry about overlapping calls. But if the slot we call takes longer time than the time we have set to rerun the slot, there will be overlapping calls. To deal with this we can use Try and Finally as shown below.

def start(self):
    self.video = Video(cv2.VideoCapture(0))
    self._timer = QtCore.QTimer(self)
    try:
        self._timer.timeout.connect(self.play)
    finally:
        self._timer.start(10)
        self.update()

Now the timer will only start couonting 10 ms after self._timer.timeout.connect(self.play) is finished.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值