QML显示界面帧率(FPS)的方法

头文件: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
    }
}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值