Python 桌面 FPS 显示在标签中

Python desktop FPS displaying in label

我无法在标签上显示当前帧率。 问题是我希望它循环并永远改变,而不是设置一次。我的想法是循环它,但直到 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()

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

我认为您因此需要做的是使用 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 class 的方法,我们得到:

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的方法才能被timer的信号调用。

现在应该可以满足您的需求了。由于我没有你正在使用的 UI 文件,我不得不制作一个与你的略有不同的脚本,所以希望我已经转换回来了,一切正常!