Connecting OpenGL in QT

Let's consider an example of connecting the OpenGL graphics library to a QT project. I will try to provide the most accessible information for a quick start. Here we will only consider the example of connection and rendering of a simple scene. In the following notes, we will add camera rotation and so on.

So... Let's go.

The most convenient way to connect is to use the built-in QT tools. Of course, there are other options - Glut (FreeGlut), Glaux (only for Windows), glu, etc. - but they are not the easiest ones, and they are not suitable for OOP (object-oriented programming) (you can try to force it, but it rarely leads to good results - for example, it is unlikely to use a method as a callback).

To connect OpenGL to the project, you first need to add the following line to the *pro file:

QT += opengl
 

Now let's create a class that will render a 3D image. It should be a subclass of QGLWidget:

#include <QGLWidget>
#include <GL/gl.h>

class WOpengl: public QGLWidget { public: WOpengl(); };

Now let's override the methods

void initializeGL();
void resizeGL(int nWidth, int nHeight);
void paintGL();

The first method is called when the window is initialized, the second one is called when the window size changes, and the third one is the "working" method - it contains the actual rendering procedure.

Examples of overridden methods:

voidWOpengl::initializeGL()
{

//Set the background color in the OpenGL window qglClearColor(Qt::black);

//Set the polygon rendering mode - front and back, //fully filled polygons //(you can also just display the outline) glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); }

void WOpengl::resizeGL(int nWidth, int nHeight) {

//Set the viewport. The last two parameters are the same - //to preserve proportions on wide screens //(you can experiment) glViewport(0, 0, nHeight, nHeight);

//Set the matrix mode glMatrixMode(GL_PROJECTION);

//Load the matrix glLoadIdentity(); }

void WOpengl::paintGL() { //Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//Set the matrix mode glMatrixMode(GL_PROJECTION);

//Load the matrix glLoadIdentity();

//Draw here - for convenience, in a separate function scene();

//Display on the screen swapBuffers(); }

Now we need to describe a function that will draw something. For example,

void WOpengl::scene()
{
  //Set the color of the image
 qglColor(Qt::green);

//Begin rendering, the argument means rendering a rectangle. //Each glVertex3f call specifies one vertex of the rectangle glBegin(GL_QUADS); glVertex3f(0.51, 0.51, 0.51); glVertex3f(-0.51, 0.51, 0.51); glVertex3f(-0.51, -0.51, 0.51); glVertex3f(0.51, -0.51, 0.51); glEnd(); }

So... That's all for now. As a result, we have a 3D window with a rectangle rendered on it.

3DIn the next note, we will learn how to rotate the scene.

You can find the source code of the completed project here: simple_3D