1 /****************************************************************************
3 ** Copyright (C) 2015 The Qt Company Ltd.
4 ** Contact: http://www.qt.io/licensing/
6 ** This file is part of the documentation of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see http://www.qt.io/terms-conditions. For further
15 ** information use the contact form at http://www.qt.io/contact-us.
17 ** GNU Free Documentation License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Free
19 ** Documentation License version 1.3 as published by the Free Software
20 ** Foundation and appearing in the file included in the packaging of
21 ** this file. Please review the following information to ensure
22 ** the GNU Free Documentation License version 1.3 requirements
23 ** will be met: http://www.gnu.org/copyleft/fdl.html.
26 ****************************************************************************/
29 \example opengl/hellogl
30 \title Hello GL Example
32 \brief The Hello GL example demonstrates the basic use of the OpenGL-related classes
35 \image hellogl-example.png
37 Qt provides the QGLWidget class to enable OpenGL graphics to be rendered within
38 a standard application user interface. By subclassing this class, and providing
39 reimplementations of event handler functions, 3D scenes can be displayed on
40 widgets that can be placed in layouts, connected to other objects using signals
41 and slots, and manipulated like any other widget.
45 \section1 GLWidget Class Definition
47 The \c GLWidget class contains some standard public definitions for the
48 constructor, destructor, \l{QWidget::sizeHint()}{sizeHint()}, and
49 \l{QWidget::minimumSizeHint()}{minimumSizeHint()} functions:
51 \snippet examples/opengl/hellogl/glwidget.h 0
53 We use a destructor to ensure that any OpenGL-specific data structures
54 are deleted when the widget is no longer needed (although in this case nothing
57 \snippet examples/opengl/hellogl/glwidget.h 1
59 The signals and slots are used to allow other objects to interact with the
62 \snippet examples/opengl/hellogl/glwidget.h 2
64 OpenGL initialization, viewport resizing, and painting are handled by
65 reimplementing the QGLWidget::initializeGL(), QGLWidget::resizeGL(), and
66 QGLWidget::paintGL() handler functions. To enable the user to interact
67 directly with the scene using the mouse, we reimplement
68 QWidget::mousePressEvent() and QWidget::mouseMoveEvent().
70 \snippet examples/opengl/hellogl/glwidget.h 3
72 The rest of the class contains utility functions and variables that are
73 used to construct and hold orientation information for the scene. The
74 \c logo variable will be used to hold a pointer to the QtLogo object which
75 contains all the geometry.
77 \section1 GLWidget Class Implementation
79 In this example, we split the class into groups of functions and describe
80 them separately. This helps to illustrate the differences between subclasses
81 of native widgets (such as QWidget and QFrame) and QGLWidget subclasses.
83 \section2 Widget Construction and Sizing
85 The constructor provides default rotation angles for the scene, sets
86 the pointer to the QtLogo object to null, and sets up some colors for
89 \snippet examples/opengl/hellogl/glwidget.cpp 0
91 We also implement a destructor to release OpenGL-related resources when the
94 \snippet examples/opengl/hellogl/glwidget.cpp 1
96 In this case nothing requires cleaning up.
98 We provide size hint functions to ensure that the widget is shown at a
101 \snippet examples/opengl/hellogl/glwidget.cpp 2
103 \snippet examples/opengl/hellogl/glwidget.cpp 3
104 \snippet examples/opengl/hellogl/glwidget.cpp 4
106 The widget provides three slots that enable other components in the
107 example to change the orientation of the scene:
109 \snippet examples/opengl/hellogl/glwidget.cpp 5
111 In the above slot, the \c xRot variable is updated only if the new angle
112 is different to the old one, the \c xRotationChanged() signal is emitted to
113 allow other components to be updated, and the widget's
114 \l{QGLWidget::updateGL()}{updateGL()} handler function is called.
116 The \c setYRotation() and \c setZRotation() slots perform the same task for
117 rotations measured by the \c yRot and \c zRot variables.
119 \section2 OpenGL Initialization
121 The \l{QGLWidget::initializeGL()}{initializeGL()} function is used to
122 perform useful initialization tasks that are needed to render the 3D scene.
123 These often involve defining colors and materials, enabling and disabling
124 certain rendering flags, and setting other properties used to customize the
127 \snippet examples/opengl/hellogl/glwidget.cpp 6
129 In this example, we reimplement the function to set the background color,
130 create a QtLogo object instance which will contain all the geometry to
131 display, and set up the rendering process to use a particular shading model
134 \section2 Resizing the Viewport
136 The \l{QGLWidget::resizeGL()}{resizeGL()} function is used to ensure that
137 the OpenGL implementation renders the scene onto a viewport that matches the
138 size of the widget, using the correct transformation from 3D coordinates to
139 2D viewport coordinates.
141 The function is called whenever the widget's dimensions change, and is
142 supplied with the new width and height. Here, we define a square viewport
143 based on the length of the smallest side of the widget to ensure that
144 the scene is not distorted if the widget has sides of unequal length:
146 \snippet examples/opengl/hellogl/glwidget.cpp 8
148 A discussion of the projection transformation used is outside the scope of
149 this example. Please consult the OpenGL reference documentation for an
150 explanation of projection matrices.
152 \section2 Painting the Scene
154 The \l{QGLWidget::paintGL()}{paintGL()} function is used to paint the
155 contents of the scene onto the widget. For widgets that only need to be
156 decorated with pure OpenGL content, we reimplement QGLWidget::paintGL()
157 \e instead of reimplementing QWidget::paintEvent():
159 \snippet examples/opengl/hellogl/glwidget.cpp 7
161 In this example, we clear the widget using the background color that
162 we defined in the \l{QGLWidget::initializeGL()}{initializeGL()} function,
163 set up the frame of reference for the geometry we want to display, and
164 call the draw method of the QtLogo object to render the scene.
166 \section2 Mouse Handling
168 Just as in subclasses of native widgets, mouse events are handled by
169 reimplementing functions such as QWidget::mousePressEvent() and
170 QWidget::mouseMoveEvent().
172 The \l{QWidget::mousePressEvent()}{mousePressEvent()} function simply
173 records the position of the mouse when a button is initially pressed:
175 \snippet examples/opengl/hellogl/glwidget.cpp 9
177 The \l{QWidget::mouseMoveEvent()}{mouseMoveEvent()} function uses the
178 previous location of the mouse cursor to determine how much the object
179 in the scene should be rotated, and in which direction:
181 \snippet examples/opengl/hellogl/glwidget.cpp 10
183 Since the user is expected to hold down the mouse button and drag the
184 cursor to rotate the object, the cursor's position is updated every time
185 a move event is received.
187 \section1 QtLogo Class
189 This class encapsulates the OpenGL geometry data which will be rendered
190 in the basic 3D scene.
192 \snippet examples/opengl/shared/qtlogo.h 0
194 The geometry is divided into a list of parts which may be rendered in
195 different ways. The data itself is contained in a Geometry structure that
196 includes the vertices, their lighting normals and index values which
197 point into the vertices, grouping them into faces.
199 \snippet examples/opengl/shared/qtlogo.cpp 0
201 The data in the Geometry class is stored in QVector<QVector3D> members
202 which are convenient for use with OpenGL because they expose raw
203 contiguous floating point values via the constData() method. Methods
204 are included for adding new vertex data, either with smooth normals, or
205 facetted normals; and for enabling the geometry ready for rendering.
207 \snippet examples/opengl/shared/qtlogo.cpp 1
209 The higher level Patch class has methods for accumulating the geometry
210 one face at a time, and treating collections of faces or "patches" with
211 transformations, applying different colors or smoothing. Although faces
212 may be added as triangles or quads, at the OpenGL level all data is
213 treated as triangles for compatibility with OpenGL/ES.
215 \snippet examples/opengl/shared/qtlogo.cpp 2
217 Drawing a Patch is simply acheived by applying any transformation,
218 and material effect, then drawing the data using the index range for
219 the patch. The model-view matrix is saved and then restored so that
220 any transformation does not affect other parts of the scene.
222 \snippet examples/opengl/shared/qtlogo.cpp 3
224 The geometry is built once on construction of the QtLogo, and it is
225 paramaterized on a number of divisions - which controls how "chunky" the
226 curved section of the logo looks - and on a scale, so larger and smaller
227 QtLogo objects can be created without having to use OpenGL scaling
228 (which would force normal recalculation).
230 The building process is done by helper classes (read the source for full
231 details) which only exist during the build phase, to assemble the parts
234 \snippet examples/opengl/shared/qtlogo.cpp 4
236 Finally the complete QtLogo scene is simply drawn by enabling the data arrays
237 and then iterating over the parts, calling draw() on each one.
239 \section1 Window Class Definition
241 The \c Window class is used as a container for the \c GLWidget used to
244 \snippet examples/opengl/hellogl/window.h 0
246 In addition, it contains sliders that are used to change the orientation
247 of the object in the scene.
249 \section1 Window Class Implementation
251 The constructor constructs an instance of the \c GLWidget class and some
252 sliders to manipulate its contents.
254 \snippet examples/opengl/hellogl/window.cpp 0
256 We connect the \l{QAbstractSlider::valueChanged()}{valueChanged()} signal
257 from each of the sliders to the appropriate slots in \c{glWidget}.
258 This allows the user to change the orientation of the object by dragging
261 We also connect the \c xRotationChanged(), \c yRotationChanged(), and
262 \c zRotationChanged() signals from \c glWidget to the
263 \l{QAbstractSlider::setValue()}{setValue()} slots in the
264 corresponding sliders.
266 \snippet examples/opengl/hellogl/window.cpp 1
268 The sliders are placed horizontally in a layout alongside the \c GLWidget,
269 and initialized with suitable default values.
271 The \c createSlider() utility function constructs a QSlider, and ensures
272 that it is set up with a suitable range, step value, tick interval, and
273 page step value before returning it to the calling function:
275 \snippet examples/opengl/hellogl/window.cpp 2
279 The \c GLWidget class implementation shows how to subclass QGLWidget for
280 the purposes of rendering a 3D scene using OpenGL calls. Since QGLWidget
281 is a subclass of QWidget, subclasses of QGLWidget can be placed in layouts
282 and provided with interactive features just like normal custom widgets.
284 We ensure that the widget is able to correctly render the scene using OpenGL
285 by reimplementing the following functions:
288 \o QGLWidget::initializeGL() sets up resources needed by the OpenGL implementation
290 \o QGLWidget::resizeGL() resizes the viewport so that the rendered scene fits onto
291 the widget, and sets up a projection matrix to map 3D coordinates to 2D viewport
293 \o QGLWidget::paintGL() performs painting operations using OpenGL calls.
296 Since QGLWidget is a subclass of QWidget, it can also be used
297 as a normal paint device, allowing 2D graphics to be drawn with QPainter.
298 This use of QGLWidget is discussed in the \l{2D Painting Example}{2D Painting}
301 More advanced users may want to paint over parts of a scene rendered using
302 OpenGL. QGLWidget allows pure OpenGL rendering to be mixed with QPainter
303 calls, but care must be taken to maintain the state of the OpenGL implementation.
304 See the \l{Overpainting Example}{Overpainting} example for more information.