In this post I am going to share the source code and explain a very simple example project that can be used as a starting point for anyone who wants to begin using OpenGL in Qt. As it is seen in the picture, this program draws a single place on the screen and allows you to rotate it in all directions.
Note that in this example no Shaders are present which also makes this example quite simple to understand but in real projects there is no running from them. So keep it mind, this is probably the most simple Qt+OpenGL example you can find.
First of all, you need to create a subclass of QOpenGLWidget and write the following functions:
void resizeGL(int width, int height);
As you will see in the project source code, I’ve named this new class QGLBegin. The reason for creating this class is that you want to add a QOpenGLWidget to your MainWindow using Qt Designer and then promote it to QGLBegin. This will allow a convenient way of adding OpenGL widgets to your windows.
initializeGL function is used for all initializations. According to Qt Documentation “This function should set up any required OpenGL resources and state.” which simply means it will be called once, so setup any thing that needs to be taken care of before everything else. In our case we just include the following in our initialization.
glClearColor(0.0, 0.0, 0.0, 0.0);glEnable(GL_LIGHTING);