Reader small image

You're reading from  Qt 6 C++ GUI Programming Cookbook - Third Edition

Product typeBook
Published inApr 2024
PublisherPackt
ISBN-139781805122630
Edition3rd Edition
Right arrow
Author (1)
Lee Zhi Eng
Lee Zhi Eng
author image
Lee Zhi Eng

Lee Zhi Eng is a self-taught programmer who worked as an artist and programmer at several game studios before becoming a part-time lecturer for 2 years at a university, teaching game development subjects related to Unity and Unreal Engine. He has not only taken part in various projects related to games, interactive apps, and virtual reality but has also participated in multiple projects that are more oriented toward software and system development. When he is not writing code, he enjoys traveling, photography, and exploring new technologies.
Read more about Lee Zhi Eng

Right arrow

OpenGL Implementation

In this chapter, we will learn how to use Open Graphics Library (OpenGL), a powerful rendering application program interface (API), and combine it with Qt. OpenGL is a cross-language, cross-platform API for drawing 2D and 3D graphics on screen through the graphics processing unit (GPU) within our computer’s graphics chip. In this chapter, we will be learning about OpenGL 3 instead of 2 because, even though the fixed-function pipeline is easier for beginners to grasp compared to the newer programmable pipeline, it is considered legacy code and has been deprecated by most modern 3D rendering software. Qt 6 supports both versions, so there should be no problem switching over to OpenGL 2 if you need backward compatibility for your software.

In this chapter, we’re going to cover the following main topics:

  • Setting up OpenGL in Qt
  • Hello World!
  • Rendering 2D shapes
  • Rendering 3D shapes
  • Texturing in OpenGL
  • Basic lighting in OpenGL...

Technical requirements

The technical requirements for this chapter include Qt 6.6.1 MinGW 64-bit and Qt Creator 12.0.2. All the code used in this chapter can be downloaded from the following GitHub repository: https://github.com/PacktPublishing/QT6-C-GUI-Programming-Cookbook---Third-Edition-/tree/main/Chapter05.

Setting up OpenGL in Qt

In this recipe, we will learn how to set up OpenGL in Qt 6.

How to do it…

Follow these steps to learn how to set up OpenGL in Qt:

  1. Create a new Qt Widgets Application by going to File | New Project. Uncheck the Generate form option to avoid generating the mainwindow.ui, mainwindow.h, and mainwindow.cpp files.
  2. Open up your project file (.pro) and add the OpenGL module to your project by adding an opengl keyword behind QT +=; after that, run qmake to reload the project modules:
    QT += core gui opengl
  3. You also need to add another line in your project file so that it will load both the OpenGL and OpenGL Utilities (GLU) libraries during startup. Without these two libraries, your program will not be able to run:
    LIBS += -lopengl32 -lglu32
  4. Open up main.cpp and replace mainwindow.h with the QtOpenGL header:
    #include <QtOpenGL>
  5. Remove all of the code related to the MainWindow class from your main.cpp file and replace it with the code...

Hello World!

In this chapter, we will learn how to use OpenGL 3 with Qt 6. Common OpenGL functions such as glBegin, glVertex2f, glColor3f, glMatrixMode, and glLoadIdentity have all been removed from OpenGL 3. OpenGL 3 uses vertex buffer objects (VBOs) to send data to the GPU in batches instead of sending them one by one through functions such as glVertex2f(), which slows down the rendering while waiting for the CPU to submit the data one by one. Therefore, we will pack all of the data into VBOs and send it all in one huge package to the GPU and instruct the GPU to calculate the resulting pixels through shader programming. We will also be learning how to create simple shader programs through a C-like programming language called OpenGL Shading Language (GLSL).

How to do it…

Let’s get started by following these steps:

  1. We will create a new class called RenderWindow, which inherits from the QOpenGLWindow class. Go to File | New File, then select C++ Class under...

Rendering 2D shapes

Since we have already learned how to draw our first rectangle on screen, we will further enhance it in this section. We will take the previous example and continue from there.

How to do it…

Let’s get started by following this example:

  1. Open up renderwindow.h and add two more VBOs, one called vbo_vertices2 and another called vbo_colors, as highlighted in the following code:
    private:
        QOpenGLContext* openGLContext;
        QOpenGLFunctions* openGLFunctions;
        QOpenGLShaderProgram* shaderProgram;
        QOpenGLVertexArrayObject* vao;
        QOpenGLBuffer* vbo_vertices;
        QOpenGLBuffer* vbo_vertices2;
        QOpenGLBuffer* vbo_colors;
  2. Open up renderwindow.cpp and add the following code to the shader code, as highlighted in the following snippet:
        static const char *vertexShaderSource...

Rendering 3D shapes

We learned how to draw simple 2D shapes onscreen in the previous section. However, to fully utilize the OpenGL API, we also need to learn how to use it to render 3D images. In a nutshell, 3D images are simply illusions that are created using 2D shapes, stacked in such a way that it makes them look like they’re 3D.

How to do it...

The main ingredient here is the depth value, which determines which shapes should appear in front of or behind the other shapes. The primitive shape that is positioned behind another surface (with a shallower depth than another shape) will not be rendered (or will be partially rendered). OpenGL provides a simple way to achieve this:

  1. Let’s continue our project from the previous 2D example. Enable depth testing by adding glEnable(GL_DEPTH_TEST) to the initializeGL() function in renderwindow.cpp:
    void RenderWindow::initializeGL() {
        openGLFunctions = openGLContext->functions();
      ...

Texturing in OpenGL

OpenGL allows us to map an image (also referred to as a texture) to a 3D shape or polygon. This process is also called texture mapping. Qt 6 appears to be the best combination with OpenGL in this case because it provides an easy way to load images that belong to one of the common formats (BMP, JPEG, PNG, TARGA, TIFF, and so on), and you do not have to implement it by yourself. We will use the previous example with a spinning cube and try to map it with a texture!

How to do it…

Let’s follow these steps to learn how to use textures in OpenGL:

  1. Open up renderwindow.h and add the variables that are highlighted in the following code block:
        QOpenGLContext* openGLContext;
        QOpenGLFunctions* openGLFunctions;
        QOpenGLShaderProgram* shaderProgram;
        QOpenGLVertexArrayObject* vao;
        QOpenGLBuffer* vbo_vertices;
        ...

Basic lighting in OpenGL

In this example, we will learn how to add a simple point light to our 3D scene by using OpenGL and Qt 6.

How to do it…

Let’s get started by following these steps:

  1. Again, we will use the previous example and add a point light near the spinning cube. Open up renderwindow.h and add another variable called vbo_normals to the file:
        QOpenGLBuffer* vbo_uvs;
        QOpenGLBuffer* vbo_normals;
        QOpenGLTexture* texture;
  2. Open renderwindow.cpp and add another array called normals to the initializeGL() function:
        GLfloat normals[] = {
         0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f,
         0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f,
         0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
         0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f...

Moving an object using keyboard controls

In this section, we will be looking at 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…

To move an object using keyboard controls, follow these steps:

  1. Open up renderwindow.h and declare two floating-point numbers called moveX and moveZ. Then, declare a QVector3D variable called movement:
        QElapsedTimer* time;
        int currentTime = 0;
        int oldTime = 0;
        float deltaTime = 0;
        float rotation = 0;
        float moveX = 0;
        float moveZ = 0;
        QVector3D movement = QVector3D(0, 0, 0);
  2. We will also declare two functions called keyPressEvent() and keyReleaseEvent...

Qt Quick 3D in QML

In this recipe, we will learn how to render 3D images using Qt 6.

How to do it…

Let’s learn how to use a 3D canvas in QML by following this example:

  1. Let’s start this example by creating a new project in Qt Creator. This time around, we will go for Qt Quick Application and not the other options that we chose in the previous examples:
Figure 5.10 – Creating a new Qt Quick Application project

Figure 5.10 – Creating a new Qt Quick Application project

  1. Once the project is created, you are required to create a resource file by going to File | New File and selecting Qt | Qt Resource File under Files and Classes and name it resource.qrc:
Figure 5.11 – Creating a Qt resource file

Figure 5.11 – Creating a Qt resource file

  1. Add an image file to our project resources—we will be using it in this example. Open up resource.qrc with Qt Creator by right-clicking on it in the Projects pane and selecting Open in Editor. Once the resources file is opened...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Qt 6 C++ GUI Programming Cookbook - Third Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805122630
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Lee Zhi Eng

Lee Zhi Eng is a self-taught programmer who worked as an artist and programmer at several game studios before becoming a part-time lecturer for 2 years at a university, teaching game development subjects related to Unity and Unreal Engine. He has not only taken part in various projects related to games, interactive apps, and virtual reality but has also participated in multiple projects that are more oriented toward software and system development. When he is not writing code, he enjoys traveling, photography, and exploring new technologies.
Read more about Lee Zhi Eng