Using OpenGL and Qt in a Scene Graph
By Eric Stone | Wednesday, August 5, 2015
This blog post presents a short example program that illustrates how to use OpenGL and Qt in a scene graph. The two main goals are to show how the scene graph can be used, and more importantly, how to incorporate your own OpenGL code as part of the scene graph (as opposed to overlaying them).
The code is relatively short and commented so rather than describe it here in detail, I suggest you build and run it, and then study the code, possibly making some changes of your own. The complete source code can be downloaded from here.
The example will build with recent versions of Qt 5 on platforms that have OpenGL. When run you should see a window, which will show an image that alternates every couple of seconds.
Here is a brief overview of each of the source files:
The file classes.h defines some useful classes that are used in the implementation:
- DynamicTexture, derived from QSGDynamicTexture
- Textures, a simple struct that is used in conjunction with YUVMaterial to generate boilerplate code
- YUVMaterial, a Material class, it can be thought of as how your scene object appears visually. It can be simple colors, textures, or even be more dynamic in terms of appearance. It has a vertex shader and a fragment shader.
- TextureNode, a Geometry node that describes the shape of the geometry
The file classes.cpp has the implementation of these classes and their methods. All of the methods are quite short, the longest being DynamicTexture::updateTexture().
In the file myqmlitem.h, the new class MyQMLItem is declared derived from QQuickItem. It has a standard constructor and destructor. There is a property of type QString for the filename with getter, setter/slot, and signal methods. Finally, a method updatePaintNode is declared, which is called whenever the Scene Graph is updated or when QQuickItem::update() has been called.
In myqmlitem.cpp we have the implementation of the methods for the MyQMLItem class. The only non-trivial method is the implementation of updatePaintNode(). See the comments in the code for more details.
The file main.cpp creates a QGuiApplication, as required by Qt's event system and a QQuickView to contain the Qt Quick view. It registers the type MyQMLitem so that it can be used from QML, and sets the main QML source file to main.qml. Finally, it shows the view and calls the Qt event loop.
The QML file main.qml simply creates a top level Rectangle of a suitable size and color. Contained with it is a MyQMLItem with an image file name. A timer alternates between two different images every two seconds be setting the appropriate property.
If you need to use OpenGL and a scene graph with Qt, I hope you find this example helpful as a starting point for your own code.