FPSItem.qml 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import QtQuick 2.0
  2. import QtQuick.Window 2.2
  3. import UM 1.3 as UM
  4. // This is an QML item that shows the FPS and a running average of the FPS.
  5. Item
  6. {
  7. id: base
  8. property alias backgroundColor: background.color
  9. property alias textColor: fpsText.color
  10. property int numMeasurementsToAverage: 3
  11. width: fpsText.contentWidth + UM.Theme.getSize("default_margin").height
  12. height: fpsText.contentHeight + UM.Theme.getSize("default_margin").height
  13. Rectangle
  14. {
  15. id: background
  16. // We use a trick here to figure out how often we can get a redraw triggered.
  17. // By adding a rotating rectangle, we can increase a counter by one every time we get notified.
  18. // After that, we trigger a timer once every second to look at that number.
  19. property int frameCounter: 0
  20. property int averageFrameCounter: 0
  21. property int counter: 0
  22. property int fps: 0
  23. property real averageFps: 0.0
  24. color: UM.Theme.getColor("primary")
  25. width: parent.width
  26. height: parent.height
  27. Rectangle
  28. {
  29. width: 0
  30. height: 0
  31. NumberAnimation on rotation
  32. {
  33. from: 0
  34. to: 360
  35. duration: 1000
  36. loops: Animation.Infinite
  37. }
  38. onRotationChanged: parent.frameCounter++;
  39. visible: false
  40. }
  41. Text
  42. {
  43. id: fpsText
  44. anchors.fill:parent
  45. verticalAlignment: Text.AlignVCenter
  46. horizontalAlignment: Text.AlignHCenter
  47. color: UM.Theme.getColor("text")
  48. font: UM.Theme.getFont("default")
  49. text: "Ø " + parent.averageFps + " | " + parent.fps + " fps"
  50. }
  51. Timer
  52. {
  53. interval: 1000
  54. repeat: true
  55. running: true
  56. onTriggered:
  57. {
  58. parent.averageFrameCounter += parent.frameCounter;
  59. parent.fps = parent.frameCounter;
  60. parent.counter++;
  61. parent.frameCounter = 0;
  62. if (parent.counter >= base.numMeasurementsToAverage)
  63. {
  64. parent.averageFps = (parent.averageFrameCounter / parent.counter).toFixed(2)
  65. parent.averageFrameCounter = 0;
  66. parent.counter = 0;
  67. }
  68. }
  69. }
  70. }
  71. }