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 initializeGL(); void paintGL(); 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);
glEnable(GL_LIGHT0); glClearColor will just clear the widget with black color. And using glEnable function we enable light and lighting. Note that GL_LIGHTING must be enabled in our case because we are not going to have any Shaders. Next are paintGL and resizeGL functions. These functions do the actual drawing and how we see the objects we have drawn on the screen. glBegin and glEnd are used to specify what will be created using the vertices and normal provided between them. Qt developers can think of it like begin and end functions of a QPainter. The rest is setting the view port and configurations that affect the view port and the way the object is seen. You can download the source code and a pre-built binary using the download buttons provided below.