This is the fifth post in a series of OpenGL “tutorials” explaining how to get a triangle on your screen using as few lines of code, in as many languages, and on as many platforms as possible.

So, as should be apparent from my last two posts, I’m switching over the front end of my research system to use the Qt GUI framework.  Naturally, since I’m trying out a new platform here, I want to post a simple way to get a triangle up on the screen as quickly as possible.

You can see my previous post for suggestions on how to get Qt set up on a mac, but since the toolkit is so widely used it should be very straightforward to set it up on windows and linux as well.

#include <QApplication>
#include <QtOpenGL>

class HelloGL : public QGLWidget
{
public:
    HelloGL(QWidget *parent = NULL) : QGLWidget(parent) {}
    ~HelloGL() {}
protected:
    void initializeGL() {
        glClearColor(0, 0, 0, 0);
    }
    void resizeGL(int w, int h) {
        glViewport(0,0,w,h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        double aspect = double(w) / double(h);
        gluOrtho2D(-aspect, aspect, -1.0, 1.0);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
    }
    void paintGL() {
        glClear(GL_COLOR_BUFFER_BIT);
        glColor3f(1.0,1.0,1.0);
        glBegin(GL_TRIANGLES);
            glVertex3f(-0.5,-0.5,1.0);
            glVertex3f( 0.5,-0.5,1.0);
            glVertex3f(-0.5, 0.5,1.0);
        glEnd();
    }
    //void mousePressEvent(QMouseEvent *event);
    //void mouseMoveEvent(QMouseEvent *event);
    //void keyPressEvent(QKeyEvent *event);
};

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

    HelloGL window;
    window.resize(500,500);
    window.move(0,0);
    window.show();

    return app.exec();
}

I went ahead and filled in a full resize stub implementation here, just for the sake of robustness.  I also left some comments suggesting where you want to hook in to capture some of the input.  Of course, there are many more places to capture input, but this is enough to get some basic click and drag camera manipulation implemented.

The really nice thing about the above code, which isn’t obvious unless you’ve used Qt, is that the HelloGL object is just a QWidget.  That means you can both drop it in as a top level window (as I did in the above code), or place it into a widget layout inside another window.  This makes it super easy to start adding some basic GUI buttons, checkboxes, sliders etc. (the reason you’d be using Qt in the first place)

I also hear there’s a way to get floating widgets over the viewport, but that turned out to be a rathole that just wasted a lot of my afternoon.