Qt3D Reference Documentation

Teapot Example


The Teapot example shows how Qt3D can be used to draw a simple teapot object with a perspective camera view in C++. There is also a QML3D version of the teapot example.

We start by defining a class that inherits from QGLView, which provides some basic scene setup logic and 3D camera navigation:

 #include "qglview.h"
 #include "qglteapot.h"

 class QGLSceneNode;

 class TeapotView : public QGLView
     TeapotView(QWidget *parent = 0) : QGLView(parent), teapot(0) {}

     void initializeGL(QGLPainter *painter);
     void paintGL(QGLPainter *painter);

     QGLSceneNode *teapot;
 int main(int argc, char *argv[])
     QApplication app(argc, argv);
     TeapotView view;
     return app.exec();

When the application starts up, we set up some scene parameters in the initializeGL() function:

 void TeapotView::initializeGL(QGLPainter *painter)

The first line of the function selects a standard rendering effect that lights material colors with the default OpenGL two-sided lighting algorithm and the default light.

The teapot member variable is an instance of QGLSceneNode, which we create using QGLBuilder during initializeGL():

     QGLBuilder builder;
     builder << QGLTeapot();
     teapot = builder.finalizedSceneNode();

The QGLTeapot class represents the geometry for the teapot, which is added to the builder with the << operator.

We then call QGLBuilder::finalizedSceneNode() to finalize the object, prepare it to be uploaded to the GL server as a vertex buffer, and hand over ownership of the scene node.

We have to take care to clean up our scene after we're done with it and here that is done in the destructor:

     delete teapot;

Finally, we paint the teapot every time the window is refreshed:

 void TeapotView::paintGL(QGLPainter *painter)

The QGLView class has in-built support for camera navigation using the mouse and keyboard. By clicking and dragging the mouse, the teapot can be rotated into any position. The image on the left shows the view in its startup default position, and the image on the right shows the view after rotation using the mouse:

Return to Examples.