头文件:fpslabel.h
#ifndef FPSLABEL_H
#define FPSLABEL_H
#include <QQuickPaintedItem>
class FPSLabel : public QQuickPaintedItem
{
Q_OBJECT
Q_PROPERTY(int value READ value NOTIFY valueChanged)
public:
explicit FPSLabel(QQuickItem *parent = 0);
int value() const;
void paint(QPainter *);
signals:
void valueChanged(int);
private:
void refreshFPS();
int m_value = -1;
int m_cacheCount = 0;
QVector<qint64> m_frames;
};
#endif // FPSLABEL_H
源文件:fpslabel.cpp
#include "fpslabel.h"
#include <QPainter>
#include <QDateTime>
#include <QDebug>
FPSLabel::FPSLabel(QQuickItem *parent)
: QQuickPaintedItem(parent)
{
setFlag(QQuickItem::ItemHasContents);
}
void FPSLabel::refreshFPS()
{
qint64 currentTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
m_frames.push_back(currentTime);
while (m_frames[0] < (currentTime - 1000)) {
m_frames.pop_front();
}
int currentCount = m_frames.length();
m_value = (currentCount + m_cacheCount) / 2;
if (currentCount != m_cacheCount) {
emit valueChanged(m_value);
}
m_cacheCount = currentCount;
}
int FPSLabel::value() const
{
return m_value;
}
void FPSLabel::paint(QPainter *painter)
{
refreshFPS();
QBrush brush(Qt::yellow);
painter->setBrush(brush);
painter->setRenderHint(QPainter::Antialiasing);
painter->drawRoundedRect(0, 0, boundingRect().width(), boundingRect().height(), 0, 0);
QFont font = painter->font();
font.setPixelSize(qMin(width(), height()) * 0.6);
painter->setFont(font);
QPen pen = painter->pen();
pen.setColor(Qt::red);
painter->setPen(pen);
painter->drawText(boundingRect(), Qt::AlignCenter, QString("FPS:%1").arg(m_value));
update();
}
注册控件:main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "fpslabel.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
// 注册控件
qmlRegisterType<FPSLabel>("HelloWorld", 1, 0, "FPSLabel");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
显示用例:main.qml
import QtQuick 2.4
import QtQuick.Window 2.2
import HelloWorld 1.0
Window {
visible: true
width: 800
height: 640
title: qsTr("Hello World")
color: "black"
FPSLabel {
width: 100
height: 50
}
}