Show FPS in QML

后端 未结 2 1453
予麋鹿
予麋鹿 2021-02-04 14:42

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++.

I already

2条回答
  •  有刺的猬
    2021-02-04 15:20

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

    Here an example.

    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 _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)
                }
        }
    

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

提交回复
热议问题