如何设置PyQt5 Qtimer以指定的时间间隔更新?

Fre*_*tri 2 python pyqt qtimer pyqt5

我想根据 15 FPS 的帧速率更新 Qtimer - 所以我的 def update(): 每 0,06 秒接收一个信号。你能帮助我吗?我在下面附加了一个代码示例,其中我的 setInterval 输入是 1/15,但我不知道这是否是正确的方法。谢谢。

from PyQt5 import QtCore

def update():
    print('hey')

fps = 15
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.setInterval(1/fps)
timer.start()
Run Code Online (Sandbox Code Playgroud)

eyl*_*esc 6

您有以下错误:

  • setInterval()接收的时间以毫秒为单位,因此您必须将其更改为timer.setInterval(1000/fps)

  • 与许多 Qt 组件一样,QTimer 需要您创建 QXApplication 并启动事件循环,在本例中 QCoreApplication 就足够了。

import sys

from PyQt5 import QtCore


def update():
    print("hey")


if __name__ == "__main__":

    app = QtCore.QCoreApplication(sys.argv)

    fps = 15
    timer = QtCore.QTimer()
    timer.timeout.connect(update)
    timer.setInterval(1000 / fps)
    timer.start()

    app.exec_()
Run Code Online (Sandbox Code Playgroud)