How to set up a 30fps loop in C++/Qt

让人想犯罪 __ 提交于 2021-01-28 19:30:11

问题


I am currently developing a small game/simulation for school in C++ with Qt and I have some background with Java. My question is how to setup a basic gameloop with Qt in an 800/600 window. I tried drawing into a GraphicsView-window with overriding the paintEvent but I can't set up a loop like that and I have some kind of mistake with overriding it.

#include "mainwindow.h"
#include <QGraphicsView>
#include "graphicsview.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    resize(800, 600);
    setWindowTitle("A* Pathfinder");
    gView = new GraphicsView(this);
    setCentralWidget(gView);
}

MainWindow::~MainWindow()
{

}

GraphicsView-class:

#include "graphicsView.h"

void GraphicsView::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.drawLine(10,10, 100,100);
}

graphicsView.h:

#ifndef GRAPHICSVIEW_H
#define GRAPHICSVIEW_H

#endif // GRAPHICSVIEW_H
#include <QGraphicsView>

class GraphicsView : public QGraphicsView
{
  protected:
    void paintEvent(QPaintEvent *event);
};

Sorry if similar questions got asked already but I am really stuck and can't find help for my specific case. Again, I want an 800x600 window in which I can draw graphics at 30fps.


回答1:


First of all you are heading the wrong direction - you do not need to override QGraphicsView, a stock one suffices. You do not need to override the paintEvent() - that doesn't do what you think it does. You don't render your scene there, that's the code which renders only the frame for the view - how the empty view looks, not what the view contains.

If you have custom drawing which is not provided by stock graphics items (such as rectangles, text, arcs and whatnot) you need to implement your own QGraphicsItem and implement its paint() function - that's how it works, every item is responsible for its painting, the scene just manages all items, the view just visualizes the scene.

You definitely don't want a timer firing at a fixed rate, that is a very naive and poor solution. It doesn't account for the time rendering and game logic processing takes, and if you want a steady frame rate, you do need to account for those variables.

30 FPS means you will have to churn out a frame every 33.33 msec. So you need to schedule every subsequent frame based on how long the previous took. For example, if the previous frame took 15 msec, you need to schedule the next in 33.33 - 15 msec, achieving finer grained control and steadier framerate as long as your CPU can keep up.

You can use the static function QTimer::singleShot() to schedule every subsequent frame with a custom interval.



来源:https://stackoverflow.com/questions/40075382/how-to-set-up-a-30fps-loop-in-c-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!