Moving an object using keyboard controls
In this topic we'll be looking at is how to move an object in OpenGL using keyboard controls. Qt provides an easy way to detect keyboard events using virtual functions, namely keyPressEvent()
and keyReleaseEvent()
. We will be using the previous example and adding to it.
How to do it…
Open up
mainwindow.h
and declare two floating point numbers calledmoveX
andmoveZ
:private: QOpenGLContext* context; QOpenGLFunctions* openGLFunctions; float rotation; GLuint texID[1]; float moveX; float moveZ;
After that, declare the
keyPressEvent()
function, like so:public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void keyPressEvent(QKeyEvent *event);
Then, open up
mainwindow.cpp
and set the default values for the two variables we just declared:MainWindow::MainWindow(QWidget *parent) { setSurfaceType(QWindow::OpenGLSurface); QSurfaceFormat format; format.setProfile(QSurfaceFormat::CompatibilityProfile); format.setVersion(2...