Qt + OpenGL Code Example

This article is from August 2009; please see the updated and more detailed version here.

I wanted to develop a game using OpenGL but I was having trouble deciding on a windowing library. Somebody suggested I try Qt, so I decided to give it another shot. I heard it was good, but the editor it came with was so foreign and unintuitive. Unfortunately, this overshadowed what a beautiful library Qt really is! It takes a little getting used to, but it really is well designed. Turns out Netbeans 6.8 (and perhaps earlier versions) have support for Qt, so it’s pretty easy to get set up. It’s probably way too early to be posting any code, but I’m going to anyways because I’m way too excited about this (yeah, I live a sad life).

main.cpp

#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();
}

GLWidget.h

#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 */

All those functions you see above will get called for you automatically. No need to register any callbacks!

GLWidget.cpp

#include <QtGui/QMouseEvent>
#include "GLWidget.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;
    }
}

It just draws a red triangle and tracks your mouse movement. You need setMouseTracking(true); in order for the mouse move callback to fire when you aren’t holding a button down. I need this for my game.

Anyway, that’s all I’ve got so far, but that should get you up and running with Qt + OpenGL anyway, the rest is native OpenGL and your typical game layout; you shouldn’t need too much more Qt-specific stuff. Although, Qt does seem to have some nice OpenGL helpers and other neat stuff I have to dig into yet :)

Leave a comment if you need some help getting set up on Netbeans/Ubuntu: there are a couple quirks but nothing too terrible.

32 thoughts on “Qt + OpenGL Code Example

  1. printf was not declared in this scope….

    include

    helped and printf seam to be buffered, so you can mention about it in tutorial

    thx for tutorial

  2. I am coming from a C++ and QT orientation. Happened to run into your page where OpenGL integration with QT is discussed. Great topic.

    I tried downloading the code you had shown above into my C++ ready netbeans IDE to see if it would run on its own. Unfortunately, it failed. I believe some OpenGL library for windows is required.

    What to install for OpenGL? How? Perhaps that will enable the above code to run.

  3. Hey Sai, you need to make sure in your .pro file you have this line: QT = core gui opengl that tells Qt to use the OpenGL module You also need to make sure you are linking to the opengl32.lib and glu32.lib You can right click on the project folder on the left and then click “Add library” Just add both those libraries by pasting in their respective paths. Hope that helps!

  4. Hi guys,

    Thanks for answering him, Art! I’ve forgotten what the process is myself, it’s been awhile since I’ve done any C++ programming, nevermind Qt + OpenGL!

    Mark

  5. Looks nice. But when i want to compile it, he says that he didn’t found the function gluOrtho2D. What can i do??

  6. One of the few examples that doesn’t use QMainWindow to connect a QGLWidget to a QApplication. Just what I was looking for. Thank you!

  7. Albrecht – Replace gluOrtho2D with glOrtho should solve your problem. Be sure to add #include

  8. Thanks ..it works fine… Additional changes include adding stdio.h header file and adding opengl in pro file as mentioned in previous comments

  9. Does it have a good performance? I’m thinking about to develop a game and it’s gonna be heavy to run, do you know if it’s a good idea to use Qt?

  10. I don’t have any benchmarks for you, but considering it’s C++ and OpenGL, I’m going to go ahead and say “yes”. OpenGL runs on your GPU, and it’s pretty low-level, so as long as you’ve coded your game properly, it should be pretty optimally efficient (your only other comparable choice is DirectX, which is Windows only). Qt, on the other hand, I’m fairly certain is going to be more efficient than GUI libraries written in other languages. Compared to other C++ GUI libraries, I can’t say for certain, but it is developed by Nokia, is pretty mature, and is used in KDE (the desktop environment used by several linux distros such as Kubuntu). Furthermore, it’s cross-platform. I doubt you’ll get much more bang for you buck.

    That said, depending on your experience, you may want a more comprehensive game library. OpenGL and Qt aren’t game libraries; you’ll have to code everything yourself. That’s why I chose them as my base; there’s no cruft, just what I write.

  11. i got an error of glortho2D which i replaced with glortho as suggested here in comments, but now it says No executables specified and then it asks me to specify executable by asking me a location for exectuable.

  12. but yes i couldnt add any #include because you didnt mention which include file to include….? tried fining something with #include glortho…… but couldnt find anything with it

  13. i have trouble in this command :

    unused parameter ‘event’ in

    void GLWidget::mousePressEvent(QMouseEvent *event) { }

    please help me to my email. thank you.

  14. With this problem unused parameter ‘event’ in

    void GLWidget::mousePressEvent(QMouseEvent *event) { }

    I have solved myseld before i only copied from main.cpp not the whole script only this

    QApplication app(argc, argv);

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

    return app.exec();

    because the original #include above already the same but that makes it some problem so i copied the whole one.

    I hope this could give some solution to the others. thank you.

  15. @Iqbal: You’re reading a very old version of this tutorial. Follow the link in the big yellow box at the top of this post.

  16. Hi Mark, first well done man u did a very gud job..

    Actually i am very new to Opengl but using Qt from last one year. i want to develop stereo image visualizer with Qt + Opengl … can u plz help me .. it is very helpful if u give me ur email id so i can directly send u my Query … thanx

  17. Hi Anuj, I’m glad you liked my tutorial, but sorry, no, I don’t provide personal 1-on-1 help. If you have a specific question you’re welcome to ask it here or I highly recommend Stackoverflow.com.

  18. Hi Mark! Im also interested in game developement, so I have a few questions related to that:) Does QT work with non-fixed pipeline openGL? Does QT support things like get the passed time in milliseconds(or CPU thicks)? Can I make a fullscreen openGL window with it?

    +Is QT free even if I use it to make stuff that I will sell?(like games) Thanks! And thanks for the code!

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>