在 QML 中显示 FPS [英] Show FPS in QML

查看:18
本文介绍了在 QML 中显示 FPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单"的方式可以在 QML/c++ 应用程序中显示 FPS(帧速率).所有动画和视图都在 QML 中完成,应用程序逻辑在 c++ 中.

Is there a "simple" way to show the FPS (frame rate) in a QML/c++ application. All animations and views are done in QML and the application logic is in c++.

在启动应用程序之前,我已经尝试在 Linux 中设置 QML_SHOW_FRAMERATE 但没有帮助:

I already tried setting QML_SHOW_FRAMERATE in Linux before starting the application but it didn't help:

export QML_SHOW_FRAMERATE=1

推荐答案

您必须创建自己的 FPS QQuickItem(或 QQuickPaintedItem)并在 main.cpp 中注册才能在 QML 代码中使用.

You have to create your own FPS QQuickItem (or QQuickPaintedItem) and register in your main.cpp to be available in your QML code.

这里是一个例子.

class FPSText: public QQuickPaintedItem
{
    Q_OBJECT
    Q_PROPERTY(int fps READ fps NOTIFY fpsChanged)
public:
    FPSText(QQuickItem *parent = 0);
    ~FPSText();
    void paint(QPainter *);
    Q_INVOKABLE int fps()const;

signals:
    void fpsChanged(int);

private:
    void recalculateFPS();
    int _currentFPS;
    int _cacheCount;
    QVector<qint64> _times;
};

FPSText::FPSText(QQuickItem *parent): QQuickPaintedItem(parent), _currentFPS(0), _cacheCount(0)
{
    _times.clear();
    setFlag(QQuickItem::ItemHasContents);
}

FPSText::~FPSText()
{
}

void FPSText::recalculateFPS()
{
    qint64 currentTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
    _times.push_back(currentTime);

    while (_times[0] < currentTime - 1000) {
        _times.pop_front();
    }

    int currentCount = _times.length();
    _currentFPS = (currentCount + _cacheCount) / 2;
    qDebug() << _currentFPS;

    if (currentCount != _cacheCount) fpsChanged(_currentFPS);

    _cacheCount = currentCount;
}

int FPSText::fps()const
{
    return _currentFPS;
}

void FPSText::paint(QPainter *painter)
{
    recalculateFPS();
    //qDebug() << __FUNCTION__;
    QBrush brush(Qt::yellow);

    painter->setBrush(brush);
    painter->setPen(Qt::NoPen);
    painter->setRenderHint(QPainter::Antialiasing);
    painter->drawRoundedRect(0, 0, boundingRect().width(), boundingRect().height(), 0, 0);
    update();
}

qml:

FPSText{
        id: fps_text
        x:0
        y: 0;
        width: 200
        height: 100
        Text {
                anchors.centerIn: parent
                text: fps_text.fps.toFixed(2)
            }
    }

您可以通过快速搜索获得 Internet 中的任何其他实现.

You can get any other implementation in Internet with a quick search.

这篇关于在 QML 中显示 FPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆