标签中显示的Python桌面FPS

时间:2018-07-24 00:03:03

标签: python label pyqt5 frame-rate

我无法在标签上显示当前fps。 问题是我希望它循环播放并不断更改,而不是设置一次。我的想法是循环它,但是直到sys.exit()这样的控件如我的label_fps才出现。

import sys
import time
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QDialog
from main_view import Ui_MainWindow


class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)


def main():
    app = QtWidgets.QApplication(sys.argv)
    application = ApplicationWindow()
    application.show()

    def fps_display():
        start_time = time.time()
        counter = 1
        # All the logic()
        time.sleep(0.1)
        time_now = time.time()
        fps = str((counter / (time_now - start_time)))
        application.ui.label_fps.setText(fps)
    #while(True): does not work
    fps_display()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:0)

正如您所指出的,在调用sys.exit()之前,不会显示Qt应用程序,因此您不能在此之前陷入循环。

我认为您因此需要使用QTimer。这将每 n 毫秒发出一个信号。然后可以将该信号连接到您的fps_display()函数,以便每次发出该信号时都会调用它。例如,您可以创建一个QTimer,它使用以下命令每0.1秒发射一次信号:

timer = QTimer()
timer.setInterval(100)  # 100 milliseconds = 0.1 seconds
timer.start()  # Set the timer running

计时器用尽时将发出的信号为timeout()。因此,正是我们要将此信号连接到处理FPS标签更新的功能上,这样:

timer.timeout.connect(fps_display)

现在,将它们放在一起并移动fps_display()的位置,使其成为ApplicationWindow类的方法,我们得到:

import sys
import time
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QDialog
from PyQt5.QtCore import QTimer, pyqtSlot  # Import new bits needed
from main_view import Ui_MainWindow


class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Add in creating and connecting the timer 
        self.timer = QTimer()
        self.timer.setInterval(100)  # 100 milliseconds = 0.1 seconds
        self.timer.timeout.connect(self.fps_display)  # Connect timeout signal to function
        self.timer.start()  # Set the timer running

    @pyqtSlot()  # Decorator to tell PyQt this method is a slot that accepts no arguments
    def fps_display(self):
        start_time = time.time()
        counter = 1
        # All the logic()
        time.sleep(0.1)
        time_now = time.time()
        fps = str((counter / (time_now - start_time)))
        self.ui.label_fps.setText(fps)


def main():
    app = QtWidgets.QApplication(sys.argv)
    application = ApplicationWindow()
    application.show()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

为了方便起见,我已经移动了fps_display(),但这绝不是要通过计时器信号调用的ApplicationWindow方法。

现在希望该功能可以完成您要执行的操作。我不得不制作一个与您的脚本稍有不同的脚本,因为我没有您正在使用的UI文件,因此希望我可以将其转换回过去,并且一切正常!