Using OpenGL with Qt: A Tutorial with Code Examples and Screenshots

My last tutorial on this subject was written almost thee years ago, and it’s still the most popular article on this blog, yet I’m not sure even I could follow it. Thus, I’m going through the steps again with the latest versions of NetBeans (7.1.2) and Qt (4.8.1), this time taking screenshots along the way.

Download and Installation

NetBeans

The first step is always to get the tools we need. I will be using NetBeans, but there is also a Qt plugin for Visual Studio if that’s what you prefer. I’m also developing on Windows, but the reason you’ve probably chosen these libraries is because they’re cross-platform, so you should be able to follow along on any OS.

So go ahead and download NetBeans, if you haven’t already.

If you’re not on Windows, be sure to change the “Platform” in the top right, if it doesn’t pre-select it for you.

If you fire up NetBeans now and try to create a new project, you’re going to get this error message:

We need a C++ compiler; there isn’t one bundled with NetBeans. Qt requires us to use the MinGW compiler; more specifically, we have to use the one that comes bundled with Qt. I tried installing it separately, but couldn’t get it to work. Unfortunately, this also means we need to download the full Qt SDK to get everything to work right, not just the library portion.

Qt SDK

Go to the Qt downloads page and download the installer for your OS. I chose the offline installer, but I’m sure the “online” one will work fine too. The Windows version is 1.7 GB, so it may take awhile on a slow connection.

When you get to the “Select Components” step, make sure you check off “MinGW 4.4” under the “Miscellenous” section. Here are the options I chose:

MSYS Make

MinGW Make doesn’t work apparently (according to the NetBeans configuration guide). They recommend MSYS, so we have to install that separately too.

Download the MSYS installer and run it. It’s probably best to leave the defaults; these libraries are picky about paths, particularly spaces in them. Answer the questions it asks:

If all went well, you should get a message like this:

It has a bit of a sense of humor.

Environment Variables

Qt depends on some libraries (.dlls) to run your application. You need to tell Windows where to find these files unless you intend on including them with every compiled application.

Open your Environment Variables and edit the “PATH” for your user account. Add “C:\QtSDK\Desktop\Qt\4.7.4\mingw\lib” to the end, or where ever you installed them to. Directories are separated by semi-colons.

Configuring Netbeans

Now we have to tell NetBeans where to find all these tools.

Open up NetBeans and then go to Tools -> Options. Switch over to the C/C++ tab. On the left side, under “Tool Collection”, click “Add…”. For the Base Directory choose the path to the MinGW bin folder.

It should auto-select the Tool Collection Family for you. Name the collection “MinGW_Qt” and click “OK”.

It should fill in all the paths for you. If it doesn’t, click “Restore Defaults”. I don’t think mine found QMake, so you may have to fill that one in yourself. It should be in a path similar to “C:\QtSDK\Desktop\Qt\4.7.4\mingw\bin\qmake.exe”.

New Project

Once that’s all done, we should be ready to start our new project.

Press Ctrl+Shift+N or click the button on the toolbar.

Choose “C/C++ Qt Application”; it will configure most things for us.

On the next page, just make sure you choose our “MinGW_Qt” Tool Collection, if you have others setup.

This should compile and run now, but it won’t do anything. Before we go any further though, there’s one more thing we have to configure, since we want to use OpenGL.

Right-click your project name under the Project tree view on the left and click “Properties”. Under Build/Qt, check off “QtOpenGL” and click “OK”.

The Code

Now that our project is set up, we’re finally ready to write some code. We’ll re-use the example from my last tutorial.

Open up “main.cpp” and replace it with this:


#include <QtGui/QApplication>
#include <QtOpenGL/QGLWidget>
#include "GLWidget.h"

int main(int argc, char *argv[]) {

    QApplication app(argc, argv);

    GLWidget window;
    window.resize(800,600);
    window.show();

    return app.exec();
}

Then right-click your project again and click New -> C++ Class.

For the Class Name put “GLWidget”. Everything else is fine.

It should add 2 new files to your project, “GLWidget.cpp” and “GLWidget.h”. It doesn’t put these in the header and source files folders for you, for some reason (bad NetBeans!), but you can click and drag them there if you want.

Now open the “GLWidget.cpp” file and throw this in it:


#include <QtGui/QMouseEvent>
#include "GLWidget.h"
#include "stdio.h"

GLWidget::GLWidget(QWidget *parent) : QGLWidget(parent) {
    setMouseTracking(true);
}

void GLWidget::initializeGL() {
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_COLOR_MATERIAL);
    glEnable(GL_BLEND);
    glEnable(GL_POLYGON_SMOOTH);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClearColor(0, 0, 0, 0);
}

void GLWidget::resizeGL(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, w, 0, h); // set origin to bottom left corner
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void GLWidget::paintGL() {
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1,0,0);
    glBegin(GL_POLYGON);
    glVertex2f(0,0);
    glVertex2f(100,500);
    glVertex2f(500,100);
    glEnd();
}

void GLWidget::mousePressEvent(QMouseEvent *event) {

}
void GLWidget::mouseMoveEvent(QMouseEvent *event) {
    printf("%d, %d\n", event->x(), event->y());
}

void GLWidget::keyPressEvent(QKeyEvent* event) {
    switch(event->key()) {
    case Qt::Key_Escape:
        close();
        break;
    default:
        event->ignore();
        break;
    }
}

And then open “GLWidget.h” and put this in it:


#ifndef _GLWIDGET_H
#define _GLWIDGET_H

#include <QtOpenGL/QGLWidget>

class GLWidget : public QGLWidget {

    Q_OBJECT // must include this if you use Qt signals/slots

public:
    GLWidget(QWidget *parent = NULL);

protected:
    void initializeGL();
    void resizeGL(int w, int h);
    void paintGL();
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
    void keyPressEvent(QKeyEvent *event);
};

#endif  /* _GLWIDGET_H */

Now compile and run that. If you’re lucky, you’ll get something that looks like this:

That’s it! Happy coding.

download-button

14 thoughts on “Using OpenGL with Qt: A Tutorial with Code Examples and Screenshots

  1. Yours includes got reformatted, “#include <QtGui/QApplication>”

    Also, with examples like these it would be awesome if you could host a sample project for people to download. Thanks Mark.

  2. @Brian,
    Good thinking. I’ve zipped the project and added a download link.

    Edit: Ugh.. the code reformatting is a bug in my code-highlighter. I don’t want to double-encode it right now in case they fix the bug. Sigh. Thanks for pointing out the issue.

  3. Thanks for hosting the project, will be helpful! I’ve never used QT, and I was having some issues trying to get the thing started. I had the includes and lib directory set, and I believe the correct libraries linked, but I was getting compile errors in Visual Studio still. So I hope looking at your project will help me solve my problem, thanks! Though, NetBeans at least tries to help you with the setup, I’m not sure if there are project templates for QT in VS.

  4. For anyone who has an issue with gluOrtho2D(0, w, 0, h); in qt:

    Just change:

    gluOrtho2D(0, w, 0, h);

    to

    glOrtho(0, w, 0, h, -1.0l, 1.0l);

  5. Note that my comment applies to users using QtCreator.

  6. Hi, I followed William Johnson’s solution to the gluOrtho2D problem, but is it normal that mouse movements trigger absolutely nothing in the application? I get no X or Y values in my output.

  7. @Thomly: Do you have a console window open? The mouse movements print to console. They might show up in your IDE’s built-in console, if it has one.

  8. hello,
    I compiled your code but when run, no window shows..

  9. Ok, figured it out, stupid bug with window resizing 😉
    Thanks for this tutorial!

  10. Thanks for all,

    but I get a black window, I changed gluOrtho2D(0,width, 0, height) for glOrtho(0, width, 0, height, -1.0, 1.0); but nothing happens.

    I follow all the code and even I use your code.

    Thanks in advance

  11. Is

    GLWidget::paintGL()

    being called? Can you maybe try writing something to the console in there?

  12. Hi …
    this tutorial is very helpful for beginners …
    thanks for uploading this …
    Now i got stuck with selection in opengl d
    will u please help me with that … all i want to do is : with mouse click making lines (up to 10) and select a line and change the color of the selected line …. here is the code of paintGL() function : will u please let me know where i m wrong :
    void glwidget::paintGL()
    {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    glLoadIdentity();

    glPointSize(5.0);
    glPushMatrix();
    if (click == 0)
    {
    glBegin(GL_POINTS);
    glColor3f(1.0,0,0);
    glVertex2d(pointarray[0][0],pointarray[0][1]);
    }
    else
    {
    if (mode == GL_SELECT)
    {
    printf(“\nInsied GL_SELECT MODE and value of ln : %d”);
    glLoadName(ln);
    ln++;
    }

    glBegin(GL_LINE_STRIP);
    if(mode==GL_SELECT)
    glColor3f(0.0,1.0,0.0);
    else
    glColor3f(1.0,0,0);

    for(int a = 0; a < s_pntArraySize -1; a++)
    {

    glVertex2d(pointarray[a][0],pointarray[a][1]);
    glVertex2d(pointarray[a+1][0],pointarray[a+1][1]);
    }
    glEnd();
    }

    glPopMatrix();

    }

  13. I do not have Netbeans Install but using Command promt to run c/c++ opengl programs.

    can u please suggest me now how i can integerate opengl and QT

Leave a Reply

Your email address will not be published. Required fields are marked *