当前位置:   article > 正文

pyqt5中QBasicTimer跟QTimer的使用_pyqt6 qbasictimer connect

pyqt6 qbasictimer connect

周期性的执行某个任务时,就需要使用计时功能。QBasicTimer跟QTimer都能实现计时功能。

QTimer可以绑定槽函数,间隔指定的时间发送一次信号,可以设置多个。

QBasicTimer使用时,需要重新timerEvent函数,QBasicTimer实例启动时需要传递两个参数,一个是触发间隔时间,另外一个触发的对象,一个程序中,出现多个QBasicTimer实例实例时,需要通过timerId()过滤发送对象。

t = QBasicTimer()
t.start(1000, self)

# start(self, int, QObject)

下面的实例演示的两种定时器的使用

  1. import sys, random
  2. from PyQt5.QtWidgets import QMainWindow, QFrame, QDesktopWidget, QApplication, QLabel, QHBoxLayout
  3. from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal, QTimer
  4. from PyQt5.QtGui import QPainter, QColor, QFont
  5. class MinWin(QMainWindow):
  6. def __init__(self):
  7. super(MinWin, self).__init__()
  8. w = QFrame()
  9. self.label = QLabel()
  10. self.label.setAlignment(Qt.AlignCenter)
  11. font = QFont('SimHei', 13)
  12. self.label.setFont(font)
  13. self.blabel = QLabel()
  14. self.blabel.setAlignment(Qt.AlignCenter)
  15. font = QFont('SimHei', 13)
  16. self.blabel.setFont(font)
  17. hLayout = QHBoxLayout()
  18. hLayout.addWidget(self.label)
  19. hLayout.addWidget(self.blabel)
  20. w.setLayout(hLayout)
  21. self.setCentralWidget(w)
  22. self.resize(900, 760)
  23. self.numCount = 0
  24. self.setContext(self.numCount)
  25. self.timer = QTimer()
  26. self.timer.start(1000)
  27. self.timer.timeout.connect(self.timerFunc)
  28. self.bTimer = QBasicTimer()
  29. # print(self.bTimer.timerId())
  30. self.bTimer.start(1000, self)
  31. self.bNumCount = 0
  32. self.blabel.setText(str(self.bNumCount))
  33. # 这里又实例化了一个QBasicTimer,他也会向timerEvent()发送事件
  34. # 在timerEvent函数中,我们使用event.timerId() == self.bTimer.timerId()进行过滤
  35. # 就可以达到为指定的计时器执行指定的动作
  36. self.b2Timer = QBasicTimer()
  37. # print(self.b2Timer.timerId())
  38. self.b2Timer.start(1000, self)
  39. self.b2NumCount = 0
  40. def setContext(self, comments):
  41. self.label.clear()
  42. self.label.setText(str(comments))
  43. def timerFunc(self):
  44. self.numCount += 1
  45. # self.setContext(self.numCount)
  46. self.label.setText(str(self.numCount))
  47. # QBasicTimer必须要重写该事件
  48. def timerEvent(self, event):
  49. if event.timerId() == self.bTimer.timerId():
  50. # 重写该事件
  51. self.bNumCount += 1
  52. self.blabel.setText(str(self.bNumCount))
  53. if event.timerId() == self.b2Timer.timerId():
  54. print(f'{self.b2Timer}发送信号')
  55. if __name__ == '__main__':
  56. app = QApplication([])
  57. tetris = MinWin()
  58. tetris.show()
  59. sys.exit(app.exec_())

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/888312
推荐阅读
相关标签
  

闽ICP备14008679号