QOpenGLWidget Class
QOpenGLWidget provides functionality for displaying OpenGL graphics integrated into a Qt application. It is very simple to use: Make your class inherit from it and use the subclass like any other QWidget, except that you have the choice between using QPainter and standard OpenGL rendering commands.
QOpenGLWidget provides three convenient virtual functions that you can reimplement in your subclass to perform the typical OpenGL tasks:
-
() — Renders the OpenGL scene. Gets called whenever the widget needs to be updated. () — Sets up the OpenGL viewport, projection, etc. Gets called whenever the widget has been resized (and also when it is shown for the first time because all newly created widgets get a resize event automatically). () — Sets up the OpenGL resources and state. Gets called once before the first time resizeGL() or paintGL() is called.
If you need to trigger a repaint from places other than paintGL() (a typical example is when using timers to animate scenes), you should call the widget’s update() function to schedule an update.
Your widget’s OpenGL rendering context is made current when paintGL(), resizeGL(), or initializeGL() is called. If you need to call the standard OpenGL API functions from other places (e.g. in your widget’s constructor or in your own paint functions), you must call makeCurrent() first.
All rendering happens into an OpenGL framebuffer object. makeCurrent() ensure that it is bound in the context. Keep this in mind when creating and binding additional framebuffer objects in the rendering code in paintGL(). Never re-bind the framebuffer with ID 0. Instead, call defaultFramebufferObject() to get the ID that should be bound.
QOpenGLWidget allows using different OpenGL versions and profiles when the platform supports it. Just set the requested format via setFormat(). Keep in mind however that having multiple QOpenGLWidget instances in the same window requires that they all use the same format, or at least formats that do not make the contexts non-sharable. To overcome this issue, prefer using QSurfaceFormat::setDefaultFormat() instead of setFormat().
Note: Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory on some platforms (for example, macOS) when an OpenGL core profile context is requested. This is to ensure that resource sharing between contexts stays functional as all internal contexts are created using the correct version and profile.
Painting Techniques
As described above, subclass QOpenGLWidget to render pure 3D content in the following way:
- Reimplement the initializeGL() and resizeGL() functions to set up the OpenGL state and provide a perspective transformation.
- Reimplement paintGL() to paint the 3D scene, calling only OpenGL functions.
It is also possible to draw 2D graphics onto a QOpenGLWidget subclass using QPainter:
- In paintGL(), instead of issuing OpenGL commands, construct a QPainter object for use on the widget.
- Draw primitives using QPainter’s member functions.
- Direct OpenGL commands can still be issued. However, you must make sure these are enclosed by a call to the painter’s beginNativePainting() and endNativePainting().
When performing drawing using QPainter only, it is also possible to perform the painting like it is done for ordinary widgets: by reimplementing paintEvent().
- Reimplement the paintEvent() function.
- Construct a QPainter object targeting the widget. Either pass the widget to the constructor or the QPainter::begin() function.
- Draw primitives using QPainter’s member functions.
- Painting finishes then the QPainter instance is destroyed. Alternatively, call QPainter::end() explicitly.
OpenGL Function Calls, Headers and QOpenGLFunctions
When making OpenGL function calls, it is strongly recommended to avoid calling the functions directly. Instead, prefer using QOpenGLFunctions (when making portable applications) or the versioned variants (for example, QOpenGLFunctions_3_2_Core and similar, when targeting modern, desktop-only OpenGL). This way the application will work correctly in all Qt build configurations, including the ones that perform dynamic OpenGL implementation loading which means applications are not directly linking to an GL implementation and thus direct function calls are not feasible.
In paintGL() the current context is always accessible by calling QOpenGLContext::currentContext(). From this context an already initialized, ready-to-be-used QOpenGLFunctions instance is retrievable by calling QOpenGLContext::functions(). An alternative to prefixing every GL call is to inherit from QOpenGLFunctions and call QOpenGLFunctions::initializeOpenGLFunctions() in initializeGL().
As for the OpenGL headers, note that in most cases there will be no need to directly include any headers like GL.h. The OpenGL-related Qt headers will include qopengl.h which will in turn include an appropriate header for the system. This might be an OpenGL ES 3.x or 2.0 header, the highest version that is available, or a system-provided gl.h. In addition, a copy of the extension headers (called glext.h on some systems) is provided as part of Qt both for OpenGL and OpenGL ES. These will get included automatically on platforms where feasible. This means that constants and function pointer typedefs from ARB, EXT, OES extensions are automatically available.
Code Examples
To get started, the simplest QOpenGLWidget subclass could look like the following:
Alternatively, the prefixing of each and every OpenGL call can be avoided by deriving from QOpenGLFunctions instead:
To get a context compatible with a given OpenGL version or profile, or to request depth and stencil buffers, call setFormat():
With OpenGL 3.0+ contexts, when portability is not important, the versioned QOpenGLFunctions variants give easy access to all the modern OpenGL functions available in a given version:
As described above, it is simpler and more robust to set the requested format globally so that it applies to all windows and contexts during the lifetime of the application. Below is an example of this:
Multisampling
To enable multisampling, set the number of requested samples on the QSurfaceFormat that is passed to setFormat(). On systems that do not support it the request may get ignored.
Multisampling support requires support for multisampled renderbuffers and framebuffer blits. On OpenGL ES 2.0 implementations it is likely that these will not be present. This means that multisampling will not be available. With modern OpenGL versions and OpenGL ES 3.0 and up this is usually not a problem anymore.
Threading
Performing offscreen rendering on worker threads, for example to generate textures that are then used in the GUI/main thread in paintGL(), are supported by exposing the widget’s QOpenGLContext so that additional contexts sharing with it can be created on each thread.
Drawing directly to the QOpenGLWidget’s framebuffer outside the GUI/main thread is possible by reimplementing paintEvent() to do nothing. The context’s thread affinity has to be changed via QObject::moveToThread(). After that, makeCurrent() and doneCurrent() are usable on the worker thread. Be careful to move the context back to the GUI/main thread afterwards.
Triggering a buffer swap just for the QOpenGLWidget is not possible since there is no real, onscreen native surface for it. It is up to the widget stack to manage composition and buffer swaps on the gui thread. When a thread is done updating the framebuffer, call update() on the GUI/main thread to schedule composition.
Extra care has to be taken to avoid using the framebuffer when the GUI/main thread is performing compositing. The signals aboutToCompose() and frameSwapped() will be emitted when the composition is starting and ending. They are emitted on the GUI/main thread. This means that by using a direct connection aboutToCompose() can block the GUI/main thread until the worker thread has finished its rendering. After that, the worker thread must perform no further rendering until the frameSwapped() signal is emitted. If this is not acceptable, the worker thread has to implement a double buffering mechanism. This involves drawing using an alternative render target, that is fully controlled by the thread, e.g. an additional framebuffer object, and blitting to the QOpenGLWidget’s framebuffer at a suitable time.
Context Sharing
When multiple QOpenGLWidgets are added as children to the same top-level widget, their contexts will share with each other. This does not apply for QOpenGLWidget instances that belong to different windows.
This means that all QOpenGLWidgets in the same window can access each other’s sharable resources, like textures, and there is no need for an extra «global share» context.
To set up sharing between QOpenGLWidget instances belonging to different windows, set the Qt::AA_ShareOpenGLContexts application attribute before instantiating QApplication. This will trigger sharing between all QOpenGLWidget instances without any further steps.
Creating extra QOpenGLContext instances that share resources like textures with the QOpenGLWidget’s context is also possible. Simply pass the pointer returned from context() to QOpenGLContext::setShareContext() before calling QOpenGLContext::create(). The resulting context can also be used on a different thread, allowing threaded generation of textures and asynchronous texture uploads.
Note that QOpenGLWidget expects a standard conformant implementation of resource sharing when it comes to the underlying graphics drivers. For example, some drivers, in particular for mobile and embedded hardware, have issues with setting up sharing between an existing context and others that are created later. Some other drivers may behave in unexpected ways when trying to utilize shared resources between different threads.
Resource Initialization and Cleanup
The QOpenGLWidget’s associated OpenGL context is guaranteed to be current whenever initializeGL() and paintGL() are invoked. Do not attempt to create OpenGL resources before initializeGL() is called. For example, attempting to compile shaders, initialize vertex buffer objects or upload texture data will fail when done in a subclass’s constructor. These operations must be deferred to initializeGL(). Some of Qt’s OpenGL helper classes, like QOpenGLBuffer or QOpenGLVertexArrayObject, have a matching deferred behavior: they can be instantiated without a context, but all initialization is deferred until a create(), or similar, call. This means that they can be used as normal (non-pointer) member variables in a QOpenGLWidget subclass, but the create() or similar function can only be called from initializeGL(). Be aware however that not all classes are designed like this. When in doubt, make the member variable a pointer and create and destroy the instance dynamically in initializeGL() and the destructor, respectively.
Releasing the resources also needs the context to be current. Therefore destructors that perform such cleanup are expected to call makeCurrent() before moving on to destroy any OpenGL resources or wrappers. Avoid deferred deletion via deleteLater() or the parenting mechanism of QObject. There is no guarantee the correct context will be current at the time the instance in question is really destroyed.
A typical subclass will therefore often look like the following when it comes to resource initialization and destruction:
This works for most cases, but not fully ideal as a generic solution. When the widget is reparented so that it ends up in an entirely different top-level window, something more is needed: by connecting to the aboutToBeDestroyed() signal of QOpenGLContext, cleanup can be performed whenever the OpenGL context is about to be released.
Note: For widgets that change their associated top-level window multiple times during their lifetime, a combined cleanup approach, as demonstrated in the code snippet below, is essential. Whenever the widget or a parent of it gets reparented so that the top-level window becomes different, the widget’s associated context is destroyed and a new one is created. This is then followed by a call to initializeGL() where all OpenGL resources must get reinitialized. Due to this the only option to perform proper cleanup is to connect to the context’s aboutToBeDestroyed() signal. Note that the context in question may not be the current one when the signal gets emitted. Therefore it is good practice to call makeCurrent() in the connected slot. Additionally, the same cleanup steps must be performed from the derived class’ destructor, since the slot or lambda connected to the signal may not invoked when the widget is being destroyed.
Note: When Qt::AA_ShareOpenGLContexts is set, the widget’s context never changes, not even when reparenting because the widget’s associated texture is going to be accessible also from the new top-level’s context. Therefore, acting on the aboutToBeDestroyed() signal of the context is not mandatory with this flag set.
Proper cleanup is especially important due to context sharing. Even though each QOpenGLWidget’s associated context is destroyed together with the QOpenGLWidget, the sharable resources in that context, like textures, will stay valid until the top-level window, in which the QOpenGLWidget lived, is destroyed. Additionally, settings like Qt::AA_ShareOpenGLContexts and some Qt modules may trigger an even wider scope for sharing contexts, potentially leading to keeping the resources in question alive for the entire lifetime of the application. Therefore the safest and most robust is always to perform explicit cleanup for all resources and resource wrappers used in the QOpenGLWidget.
Limitations and Other Considerations
Putting other widgets underneath and making the QOpenGLWidget transparent will not lead to the expected results: The widgets underneath will not be visible. This is because in practice the QOpenGLWidget is drawn before all other regular, non-OpenGL widgets, and so see-through type of solutions are not feasible. Other type of layouts, like having widgets on top of the QOpenGLWidget, will function as expected.
When absolutely necessary, this limitation can be overcome by setting the Qt::WA_AlwaysStackOnTop attribute on the QOpenGLWidget. Be aware however that this breaks stacking order, for example it will not be possible to have other widgets on top of the QOpenGLWidget, so it should only be used in situations where a semi-transparent QOpenGLWidget with other widgets visible underneath is required.
Note that this does not apply when there are no other widgets underneath and the intention is to have a semi-transparent window. In that case the traditional approach of setting Qt::WA_TranslucentBackground on the top-level window is sufficient. Note that if the transparent areas are only desired in the QOpenGLWidget, then Qt::WA_NoSystemBackground will need to be turned back to false after enabling Qt::WA_TranslucentBackground. Additionally, requesting an alpha channel for the QOpenGLWidget’s context via setFormat() may be necessary too, depending on the system.
QOpenGLWidget supports multiple update behaviors, just like QOpenGLWindow. In preserved mode the rendered content from the previous paintGL() call is available in the next one, allowing incremental rendering. In non-preserved mode the content is lost and paintGL() implementations are expected to redraw everything in the view.
Before Qt 5.5 the default behavior of QOpenGLWidget was to preserve the rendered contents between paintGL() calls. Since Qt 5.5 the default behavior is non-preserved because this provides better performance and the majority of applications have no need for the previous content. This also resembles the semantics of an OpenGL-based QWindow and matches the default behavior of QOpenGLWindow in that the color and ancillary buffers are invalidated for each frame. To restore the preserved behavior, call setUpdateBehavior() with PartialUpdate .
Note: When dynamically adding a QOpenGLWidget into a widget hierarchy, e.g. by parenting a new QOpenGLWidget to a widget where the corresponding top-level widget is already shown on screen, the associated native window may get implicitly destroyed and recreated if the QOpenGLWidget is the first of its kind within its window. This is because the window type changes from RasterSurface to OpenGLSurface and that has platform-specific implications. This behavior is new in Qt 6.4.
Once a QOpenGLWidget is added to a widget hierarchy, the contents of the top-level window is flushed via OpenGL-based rendering. Widgets other than the QOpenGLWidget continue to draw their content using a software-based painter, but the final composition is done through the 3D API.
Note: Displaying a QOpenGLWidget requires an alpha channel in the associated top-level window’s backing store due to the way composition with other QWidget-based content works. If there is no alpha channel, the content rendered by the QOpenGLWidget will not be visible. This can become particularly relevant on Linux/X11 in remote display setups (such as, with Xvnc), when using a color depth lower than 24. For example, a color depth of 16 will typically map to using a backing store image with the format QImage::Format_RGB16 (RGB565), leaving no room for an alpha channel. Therefore, if experiencing problems with getting the contents of a QOpenGLWidget composited correctly with other the widgets in the window, make sure the server (such as, vncserver) is configured with a 24 or 32 bit depth instead of 16.
Alternatives
Adding a QOpenGLWidget into a window turns on OpenGL-based compositing for the entire window. In some special cases this may not be ideal, and the old QGLWidget-style behavior with a separate, native child window is desired. Desktop applications that understand the limitations of this approach (for example when it comes to overlaps, transparency, scroll views and MDI areas), can use QOpenGLWindow with QWidget::createWindowContainer(). This is a modern alternative to QGLWidget and is faster than QOpenGLWidget due to the lack of the additional composition step. It is strongly recommended to limit the usage of this approach to cases where there is no other choice. Note that this option is not suitable for most embedded and mobile platforms, and it is known to have issues on certain desktop platforms (e.g. macOS) too. The stable, cross-platform solution is always QOpenGLWidget.
OpenGL is a trademark of Silicon Graphics, Inc. in the United States and other countries.
Member Type Documentation
[since 5.5] enum QOpenGLWidget:: UpdateBehavior
This enum describes the update semantics of QOpenGLWidget.
| Constant | Value | Description |
|---|---|---|
| QOpenGLWidget::NoPartialUpdate | 0 | QOpenGLWidget will discard the contents of the color buffer and the ancillary buffers after the QOpenGLWidget is rendered to screen. This is the same behavior that can be expected by calling QOpenGLContext::swapBuffers with a default opengl enabled QWindow as the argument. NoPartialUpdate can have some performance benefits on certain hardware architectures common in the mobile and embedded space when a framebuffer object is used as the rendering target. The framebuffer object is invalidated between frames with glDiscardFramebufferEXT if supported or a glClear. Please see the documentation of EXT_discard_framebuffer for more information: https://www.khronos.org/registry/gles/extensions/EXT/EXT_discard_framebuffer.txt |
| QOpenGLWidget::PartialUpdate | 1 | The framebuffer objects color buffer and ancillary buffers are not invalidated between frames. |
This enum was introduced or modified in Qt 5.5.
Member Function Documentation
QOpenGLWidget:: QOpenGLWidget ( QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags())
Constructs a widget which is a child of parent, with widget flags set to f.
[signal] void QOpenGLWidget:: aboutToCompose ()
This signal is emitted when the widget’s top-level window is about to begin composing the textures of its QOpenGLWidget children and the other widgets.
[signal] void QOpenGLWidget:: aboutToResize ()
This signal is emitted when the widget’s size is changed and therefore the framebuffer object is going to be recreated.
[signal] void QOpenGLWidget:: frameSwapped ()
This signal is emitted after the widget’s top-level window has finished composition and returned from its potentially blocking QOpenGLContext::swapBuffers() call.
[signal] void QOpenGLWidget:: resized ()
This signal is emitted right after the framebuffer object has been recreated due to resizing the widget.
[virtual] QOpenGLWidget::
Destroys the QOpenGLWidget instance, freeing its resources.
The QOpenGLWidget’s context is made current in the destructor, allowing for safe destruction of any child object that may need to release OpenGL resources belonging to the context provided by this widget.
Warning: if you have objects wrapping OpenGL resources (such as QOpenGLBuffer, QOpenGLShaderProgram, etc.) as members of a OpenGLWidget subclass, you may need to add a call to makeCurrent() in that subclass’ destructor as well. Due to the rules of C++ object destruction, those objects will be destroyed before calling this function (but after that the destructor of the subclass has run), therefore making the OpenGL context current in this function happens too late for their safe disposal.
QOpenGLContext *QOpenGLWidget:: context () const
Returns The QOpenGLContext used by this widget or 0 if not yet initialized.
Note: The context and the framebuffer object used by the widget changes when reparenting the widget via setParent().
GLuint QOpenGLWidget:: defaultFramebufferObject () const
Returns The framebuffer object handle or 0 if not yet initialized.
Note: The framebuffer object belongs to the context returned by context() and may not be accessible from other contexts.
Note: The context and the framebuffer object used by the widget changes when reparenting the widget via setParent(). In addition, the framebuffer object changes on each resize.
void QOpenGLWidget:: doneCurrent ()
Releases the context.
It is not necessary to call this function in most cases, since the widget will make sure the context is bound and released properly when invoking paintGL().
[override virtual protected] bool QOpenGLWidget:: event ( QEvent *e)
Reimplements: QWidget::event(QEvent *event).
QSurfaceFormat QOpenGLWidget:: format () const
Returns the context and surface format used by this widget and its toplevel window.
After the widget and its toplevel have both been created, resized and shown, this function will return the actual format of the context. This may differ from the requested format if the request could not be fulfilled by the platform. It is also possible to get larger color buffer sizes than requested.
When the widget’s window and the related OpenGL resources are not yet initialized, the return value is the format that has been set via setFormat().
QImage QOpenGLWidget:: grabFramebuffer ()
Renders and returns a 32-bit RGB image of the framebuffer.
Note: This is a potentially expensive operation because it relies on glReadPixels() to read back the pixels. This may be slow and can stall the GPU pipeline.
[virtual protected] void QOpenGLWidget:: initializeGL ()
This virtual function is called once before the first call to paintGL() or resizeGL(). Reimplement it in a subclass.
This function should set up any required OpenGL resources and state.
There is no need to call makeCurrent() because this has already been done when this function is called. Note however that the framebuffer is not yet available at this stage, so avoid issuing draw calls from here. Defer such calls to paintGL() instead.
bool QOpenGLWidget:: isValid () const
Returns true if the widget and OpenGL resources, like the context, have been successfully initialized. Note that the return value is always false until the widget is shown.
void QOpenGLWidget:: makeCurrent ()
Prepares for rendering OpenGL content for this widget by making the corresponding context current and binding the framebuffer object in that context.
It is not necessary to call this function in most cases, because it is called automatically before invoking paintGL().
[override virtual protected] int QOpenGLWidget:: metric ( QPaintDevice::PaintDeviceMetric metric) const
[override virtual protected] QPaintEngine *QOpenGLWidget:: paintEngine () const
[override virtual protected] void QOpenGLWidget:: paintEvent ( QPaintEvent *e)
Reimplements: QWidget::paintEvent(QPaintEvent *event).
Handles paint events.
Calling QWidget::update() will lead to sending a paint event e, and thus invoking this function. (NB this is asynchronous and will happen at some point after returning from update()). This function will then, after some preparation, call the virtual paintGL() to update the contents of the QOpenGLWidget’s framebuffer. The widget’s top-level window will then composite the framebuffer’s texture with the rest of the window.
[virtual protected] void QOpenGLWidget:: paintGL ()
This virtual function is called whenever the widget needs to be painted. Reimplement it in a subclass.
There is no need to call makeCurrent() because this has already been done when this function is called.
Before invoking this function, the context and the framebuffer are bound, and the viewport is set up by a call to glViewport(). No other state is set and no clearing or drawing is performed by the framework.
[override virtual protected] QPaintDevice *QOpenGLWidget:: redirected ( QPoint *p) const
[override virtual protected] void QOpenGLWidget:: resizeEvent ( QResizeEvent *e)
Reimplements: QWidget::resizeEvent(QResizeEvent *event).
Handles resize events that are passed in the e event parameter. Calls the virtual function resizeGL().
Note: Avoid overriding this function in derived classes. If that is not feasible, make sure that QOpenGLWidget’s implementation is invoked too. Otherwise the underlying framebuffer object and related resources will not get resized properly and will lead to incorrect rendering.
[virtual protected] void QOpenGLWidget:: resizeGL ( int w, int h)
This virtual function is called whenever the widget has been resized. Reimplement it in a subclass. The new size is passed in w and h.
There is no need to call makeCurrent() because this has already been done when this function is called. Additionally, the framebuffer is also bound.
void QOpenGLWidget:: setFormat (const QSurfaceFormat &format)
Sets the requested surface format.
When the format is not explicitly set via this function, the format returned by QSurfaceFormat::defaultFormat() will be used. This means that when having multiple OpenGL widgets, individual calls to this function can be replaced by one single call to QSurfaceFormat::setDefaultFormat() before creating the first widget.
Note: Requesting an alpha buffer via this function will not lead to the desired results when the intention is to make other widgets beneath visible. Instead, use Qt::WA_AlwaysStackOnTop to enable semi-transparent QOpenGLWidget instances with other widgets visible underneath. Keep in mind however that this breaks the stacking order, so it will no longer be possible to have other widgets on top of the QOpenGLWidget.
[since 5.10] void QOpenGLWidget:: setTextureFormat ( GLenum texFormat)
Sets a custom internal texture format of texFormat.
When working with sRGB framebuffers, it will be necessary to specify a format like GL_SRGB8_ALPHA8 . This can be achieved by calling this function.
Note: This function has no effect if called after the widget has already been shown and thus it performed initialization.
Note: This function will typically have to be used in combination with a QSurfaceFormat::setDefaultFormat() call that sets the color space to QSurfaceFormat::sRGBColorSpace.
This function was introduced in Qt 5.10.
[since 5.5] void QOpenGLWidget:: setUpdateBehavior ( QOpenGLWidget::UpdateBehavior updateBehavior)
Sets this widget’s update behavior to updateBehavior.
This function was introduced in Qt 5.5.
[since 5.10] GLenum QOpenGLWidget:: textureFormat () const
Returns the active internal texture format if the widget has already initialized, the requested format if one was set but the widget has not yet been made visible, or nullptr if setTextureFormat() was not called and the widget has not yet been made visible.
This function was introduced in Qt 5.10.
[since 5.5] QOpenGLWidget::UpdateBehavior QOpenGLWidget:: updateBehavior () const
Returns the update behavior of the widget.
This function was introduced in Qt 5.5.
© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.
Qt+OpenGL — Основы. Часть 1
Данная cтатья вводная, рассчитана на знакомство с Qt+OpenGL для новичков, которые планируют изучать Qt (как кросс-платформенный инструментарий разработки ПО на языке программирования C++) + OpenGL (как графическую библиотеку).
Что потребуется новичку:
1) Qt Creator (имеет хорошую встроенную документацию и подсказки во время набора кода). Скчаать
2) doc.qt.nokia.com — официальная документация на английском языке
3) doc.crossplatform.ru — документация на русском языке
4) Обязательно прочесть про Qt и OpenGL
5) Отличная статья для начала изучения
Что мы будем делать
Поскольку данная статья посвящена конкретно основам, в нашей задаче будет следующее:
1) Разобрать как создается приложение
2) Как рисовать объекты
3) Как работать с указателем мыши и событиями(нажатие клавиш на клавиатуре и на мышке)
4) Работа с таймером
5) Создадим нашу первую банальную игру. Будем с помощью таймера, случайным образом перемещать квадрат. После наведения на квадрат указателя и кликнув по нему левой кнопки мышки, в случае попадания по квадрату, будем прибавлять к полученным очкам +1.
Создаем проект
При открытии Qt Creator, начинаем создавать новый проект.
Выбираем проект Qt Widget -> GUI приложение Qt
В разделе Информация о классе снимает галочку для создания формы.
В результате действий мы получим проект с файлами:
opengl.pro — необходим для компиляции нашего проекта
mainwindow.h — для объявления всех глобальных данных
main.cpp
mainwindow.cpp — методы нашей программы
Подключение библиотек
В файле *.pro вашего проекта в строке Qt += необходимо дописать opengl для того, чтоб подключить использование библиотеки opengl. Таким же образом подключаются и другие библиотеки.
В файле mainwindow.h — если у вас имя по умолчанию выбрано, необходимо подключить:
Предопределение для нас нужных методов и переменных
Открываем mainwindow.h
В первую очередь сменим:
class MainWindow: public QMainWindow
на
class MainWindow: public QGLWidget
Это потому, что QMainWindow — класс для вывода простого окна, а т.к. мы будем работать с opengl, нам понадобится QGLWidget — это класс для вывода графики, реализующий функции библиотеки OpenGL.
Теперь предопределим переменные и методы
Так же у нас есть один слот, для того, чтоб по таймеру пересчитывать новые координаты квадрата по которому кликать.
Принцип построения изображения
QGLWidget так устроен, что при первой инициализации класса он автоматически вызывает методы в следующем порядке:
При запуске: initializeGL()->resizeGL()->paintGL()
При изменении размера окна: resizeGL()->paintGL()
updateGL() вызывает paintGL()
initializeGL — необходимо использовать для глобальных настрое построения изображения, которые нет необходимости указывать при построении кадра.
resizeGL — служит для построения размера окна. Если в ходе работы изменится размер окна, но не изменить область просмотра, то при увеличении размера можно наблюдать непредсказуемые явления.
paintGL — этот метод будет выстраивать каждый наш кадр для отображения.
Для чего двойная буферизация
PaintGL сразу картинку не рисует на экран, а заносит в буфер, а по запросу swapBuffers() заменяет текущие изображение на то, что появилось в буфере. Сама по себе буфериция позволяет более корректно заменять изображение, чтоб не происходили скачки на экране.
События клика мыши
mousePressEvent() — метод автоматически вызывается при нажатии клавиш мыши. В передаваемых параметрах можно получить различную информацию например какой именно кнопкой было сделано нажатие и по какой точке по координатам.
-Данное событие в нашем примере используется для определения куда кликнули мышью, затем если наши координаты находятся в поле квадрата, то добавляем к нашим очкам + 1 и перестраиваем наш кадр.
-Так же используем для определения начальных координат для выделения области на экране, при зажатии и перемещении указателя.
Событие перемещения указателя мыши
mouseMoveEvent() — автоматически вызывается при изменении координат указателя мыши. Но есть одно Но, по умолчанию установлено setMouseTracking(false), поэтому событие вызывается только при условии нажатия клавиш мыши, для того, чтоб метод вызывался даже без нажатия необходимо установить setMouseTracking(true).
— Данный метод мы используем для получения текущего положения указателя, чтоб перестроить выделение области или нарисовать собственный курсор.
Событие когда «отжимается» кнопка мыши
mouseReleaseEvent() — автоматически вызывается при условии «отжатия» кнопки мыши. Так же принимает различные параметры.
— В данном случае мы используем метод, чтоб стереть с экрана выделенную нами область.
Событие нажатие клавиш на клавиатуре
keyPressEvent() — метод вызывается при событии, когда нажимается кнопка на клавиатуре.
— В нашем примере, мы используем этот метод, для того, чтоб переопределить координаты нашего квадрата и переместить его в новое место.
Таймер
QTimer — позволяет нам создать поток, который будет слушать сигналы и запускать соответственные слоты.
— В данном случае мы создаем таймер, который будет ждать 750мс после чего он завершает свою работу, отправляя нам сигнал timeout() , но мы при окончании сигнала будем не останавливать работу, а снова запускать слот на переопределение координат квадрата, по которому нужно кликать для того, чтоб набрать очки.
Задание по данному материалу для усвоения.
Выложенный мной готовый код работает, но домашним заданием будет модифицировать код так, чтоб при запуске игры было приветствие, при нажатии на которое давалось минута на получение очков. По истечению минуты выводилось количество набранных очков и предлагалось сыграть еще раз.
Заключение!
Большинство из немногого написанного здесь, в нашей первой примитивной игре просто не нужно. Но хочу отметить еще раз: «Статья вводная, рассчитана на знакомство с Qt+OpenGL«. Так же если Вы заметили написанные таким образом программы можно компилировать для любой операционной среды.
Name already in use
learning-guides / openGL_tutorial / usingOpenGL.rst
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Using OpenGL in your Qt Application
Qt provides a widget called QGLWidget for rendering OpenGL Graphics, which enables you to easily integrate OpenGL into your Qt application. It is subclassed and used like any other QWidget and is cross-platform. You usually reimplement the following three virtual methods:
Qt also offers a cross-platform abstraction for shader programs called QGLShaderProgram. This class facilitates the process of compiling and linking the shader programs as well as switching between different shaders.
You might need to adapt the versions set in the example source codes to those supported by your system.
We are beginning with a small Hello World example that will have our graphics card render a simple triangle. For this purpose we subclass QGLWidget in order to obtain an OpenGL rendering context and write a simple vertex and fragment shader.
This example confirms whether we have set up our development environment properly.
The source code related to this section is located in examples/hello-opengl/ directory.
First of all, we need to tell qmake to use the QtOpenGL module. So we add:
The main() function only serves the purpose of instantiating and showing our QGLWidget subclass.
Our OpenGL widget class is defined as follows:
We want the widget to be a subclass of QGLWidget. Because we might later be using signals and slots, we invoke the Q_OBJECT macro. Additionally we reimplement QWidget::minimumSizeHint() and QWidget::sizeHint() to set reasonable default sizes.
To call the usual OpenGL rendering commands, we reimplement the three virtual functions GLWidget::initializeGL(), QGLWidget::resizeGL(), and QGLWidget::paintGL().
We also need some member variables. pMatrix is a QMatrix4x4 that keeps the projection part of the transformation pipeline. To manage the shaders, we use a QGLShaderProgram named, shaderProgram. vertices is a QVector made of QVector3Ds that stores the triangle’s vertices. Although the vertex shader will expect us to send homogeneous coordinates, we can use 3D vectors, because the OpenGL pipeline automatically sets the fourth coordinate to the default value of 1.
Now that we have defined our widget, we can finally talk about the implementation.
The constructor’s initializer list calls QGLWidget’s constructor passing a QGLFormat object. This can be used to set the capabilities of the OpenGL rendering context such as double buffering or multisampling. We are fine with the default values so we could as well have omitted the QLFormat. Qt tries to acquire a rendering context as close as possible to what we want.
Then we reimplement QWidget::sizeHint() to set a reasonable default size for the widget.
The QGLWidget::initializeGL() method gets called once when the OpenGL context is created. We use this function to set the behavior of the rendering context and to build the shader programs.
If we want to render 3D images, we need to enable depth testing. This is one of the tests that can be performed during the per-sample-operations stage. It will cause OpenGL to only display the fragments nearest to the camera when primitives overlap. Although we do not need this capability as we only want to show a plane triangle, but we can use this setting in our other examples. If you’ve omitted this statement, you might see objects in the back popping through objects in the front depending on the order the primitives are rendered. Deactivating this capability is useful if you want to draw an overlay image on top of the screen.
As an easy way to significantly improve the performance of a 3D application, we also enable face culling. This tells OpenGL to only render primitives that show their front side. The front side is defined by the order of the triangle’s vertices. You can tell what side of the triangle you are seeing by looking at its corners. If the triangle’s corners are specified in a counterclockwise order, this means that the front of the triangle is the side facing you. For all triangles that are not facing the camera, the fragment processing stage can be omited.
Then we set the background color using QGLWidget::qglClearColor(). It is a function that calls OpenGL’s glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf apha) but has the advantage of allowing any color Qt understands to be passed. The specified color will then be used in all subsequent calls to glClear(GLbitfield mask).
In the following section we are setting up the shaders. We pass the source codes of the shaders to the QGLShaderProgram, compile and link them, and bind the program to the current OpenGL rendering context.
Shader programs need to be supplied as source codes. We can use QGLShaderProgram::addShaderFromSourceFile() to let Qt handle the compilation. This function compiles the source code as the specified shader type and adds it to the shader program. If an error occurs, the function returns false, and we can access the compilation errors and warnings using QGLShaderProgram::log(). Errors will be automatically printed to the standard error output if we run the program in debug mode.
After the compilation, we still need to link the programs using QGLShaderProgram::link(). We can again check for errors and access the errors and warnings using QGLShaderProgram::log().
The shaders are then ready to be bound to the rendering context using QGLShaderProgram::bind(). Binding the program to the context means enabling it in the graphics pipeline. After this is done, every vertex that is passed to the graphics pipeline will be processed by these shaders until we call QGLShaderProgram::release() to disable them or a different shader program is bound.
Binding and releasing a program can be done several times during the rendering process, which means several vertex and fragment shaders can be used for different objects in the scene. We will therefore use these functions in the QGLWidget::paintGL() function.
Last but not least, we set up the triangles’ vertices. Note that we’ve defined the triangle with the front side pointing to the positive z direction. Having face culling enabled, we can then see this object if we look at it from viewer positions with a z value greater than this object’s z value.
Now let’s take a look at the shaders we will use in this example.
The vertex shader only calculates the final projection of each vertex by multiplying the vertex with the model-view-projection matrix.
It needs to read two input variables. The first input is the model-view-projection matrix. It is a 4×4 matrix that changes once per object and is therefore declared as a uniform mat4. We’ve named it mvpMatrix. The second variable is the actual vertex that the shader is processing. As the shader reads a new value every time it is executed, the vertex variable needs to be declared as an attribute vec4. We’ve named this variable vertex.
In the main() function, we simply calculate the resulting position that is sent to the rasterization stage using built in matrix vector multiplication.
The fragment shader simply displays a colored pixel for each fragment it is executed on.
The output of the fragment shader is the value written to the frame buffer. We called this variable fragColor. It is an instance of vec4 with one element for the red, green, and blue color value, and one element for the alpha value.
We want to use the same plain color for each pixel. Therefore we declare an input variable called color, which is a uniform vec4.
The main() function then sets the built in hl_FragColor output variable to this value.
The reimplemented QGLWidget::resizeGL() method is called whenever the widget is resized. This is why we use this function to set up the projection matrix and the viewport.
After we had checked the widget’s height to prevent a division by zero, we set it to a matrix that does the perspective projection. Luckily we do not have to calculate it ourselves. We can use one of the many useful methods of QMatrix4x4, namely QMatrix4x4::perspective(), which does exactly what we need. This method multiplies its QMatrix4x4 instance with a projection matrix that is specified by the angle of the field of view, its aspect ratio and the clipping regions of the near and far planes. The matrix we get using this function resembles the projection of a camera that is sitting in the origin of the world coordinate system looking towards the world’s negative z direction with the world’s x axis pointing to the right side and the y axis pointing upwards. The fact that this function alters its instance explains the need to first initialize it to an identity matrix (a matrix that doesn’t change the vector when applied as a transformation).
Next we set up the OpenGL viewport. The viewport defines the region of the widget that the result of the projection is mapped to. This mapping transforms the normalized coordinates on the aforementioned camera’s film to pixel coordinates within the QGLWidget. To avoid distortion, the aspect ratio of the viewport should match the aspect ratio of the projection.
Finally, we have OpenGL draw the triangle in the QGLWidget::paintGL() method.
The first thing we do is clear the screen using glClear(GLbitfield mask). If this OpenGL function is called with the GL_COLOR_BUFFER_BIT set, it fills the color buffer with the color set by glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf aplha). Setting the GL_DEPTH_BUFFER_BIT tells OpenGL to clear the depth buffer, which is used for the depth test and stores the distance of rendered pixels. We usually need to clear both buffers, and therefore, we set both bits.
As we already know, the model-view-projection matrix that is used by the vertex shader is a concatenation of the model matrix, the view matrix and the projection matrix. Just like for the projection matrix, we also use the QMatrix4x4 class to handle the other two transformations. Although we do not want to use them in this basic example, we already introduce them here to clarify their use. We use them to calculate the model-view-projection matrix, but leave them initialized to the identity matrix. This means we do not move or rotate the triangle’s frame and also leave the camera unchanged, located in the origin of the world coordinate system.
The rendering can now be triggered by calling the OpenGL function, glDrawArrays(GLenum mode, GLint first, GLsizei count). But before we can do that, we need to bind the shaders and hand over all the uniforms and attributes they need.
In native OpenGL, the programmer would first have to query the id (called location) of each input variable using the verbatim variable name as it is typed in the shader source code, and then set its value using this id and a type OpenGL understands. QGLShaderProgram instead offers a huge set of overloaded functions for this purpose which allow you to address an input variable using either its location or its name. These functions can also automatically convert the variable type from Qt types to OpenGL types.
We set the uniform values for both shaders using QGLShaderProgram::setUniformValue() by passing its name. The vertex shader’s uniform Matrix is calculated by multiplying its three components. The color of the triangle is set using a QColor instance that is automatically be converted to a vec4 for us.
To tell OpenGL where to find the stream of vertices, we call QGLShaderProgram::setAttributeArray() and pass the QVector::constData() pointer. Setting attribute arrays works in the same way as setting uniform values, but there’s one difference: we must explicitly enable the attribute array using QGLShaderProgram::enableAttributeArray(). If we do not do this, OpenGL would assume that we’ve assigned a single value instead of an array.
Finally we call glDrawArrays(GLenum mode, GLint first, GLsizei count) to do the rendering. It is used to start rendering a sequence of geometry primitives using the current configuration. We pass GL_TRIANGLES as the first parameter to tell OpenGL that each of the three vertices form a triangle. The second parameter specifies the starting index within the attribute arrays, and the third parameter is the number of indices to be rendered.
Note that if you later want to draw more than one object, you only need to repeat all of the steps (except for clearing the screen, of course) you took in this method for each new object.
You should see a white triangle on black background after compiling and running this program.
Rendering in 3D
A white triangle on black background is not very interesting and also not 3D, but now that we have a running basis, we can extend it to create a real 3D application. In this example, we will render a more complex object and implement the functionality for interactively exploring our scene.

The source code related to this section is located in examples/rendering-in-3d/ directory.
Just as with any QWidget subclass, we can use Qt’s event system to handle user input. We want to be able to view the scene in the same way we would explore a globe. By dragging the mouse across the widget, we want to change the angle that we look from. The distance to the scene shall change if we turn the mouse’s scroll wheel.
For this functionality, we reimplement QWidget::mousePressEvent(), QWidget::mouseMoveEvent(), and QWidget::wheelEvent(). The new member variables alpha, beta, and distance hold the parameters of the view point, and lastMousePosition helps us track mouse movement.
The most important new thing in this example is the employment of the view matrix. Again, we do not calculate this matrix ourselves but use the QMatrix4x4::lookAt() function to obtain this matrix. This function takes the position of the viewer, the point the viewer is looking at and a vector that defines the up direction. We want the viewer to look at the world’s origin and start with a position that is located at a certain distance (distance) along the z axis with the up direction being the y axis. We then rotate these two vertices using a transformation matrix. First we rotate them (and their coordinate system) by the alpha angle around their new rotated x axis, which tilts the camera. Note that you can also illustrate the transformation the other way around: first we rotate the vertices by the beta angle around the world’s x axis and then we rotate them by the alpha angle around the world’s y axis.
These three parameters need to be initialized in the constructor and, to account for the user’s input, we then change them in the corresponding event handlers.
In the QWidget::mousePressEvent(), we store the mouse pointer’s initial position to be able to track the movement. In the QGLWidget::mouseMoveEvent(), we calculate the pointers change and adapt the angles alpha and beta. As the view point’s parameters have changed, we call QGLWidget::updateGL() to trigger an update of the rendering context.
In the QGLWidget::wheelEvent(), we either increase or decrease the viewers distance by 10% and update the rendering again.
In order to finish this example, we only need to change our list of vertices to form a cube.
If you now compile and run this program, you will see a white cube that can be rotated using the mouse. As each of its six sides is painted in the same plane color, depth is not visible. We will work on this in the next example.
In this example, we want to color each side of the cube in different colors to enhance the illusion of three dimensionality. To archive this, we will extend our shaders in a way that allows us to specify a single color for each vertex and use the interpolation of varyings to generate the fragment’s colors. This example shows you how to communicate data from the vertex shader over to the fragment shader.

The source code related to this section is located in the examples/coloring/ directory
To tell the shaders about the colors, we specify a color value for each vertex as an attribute array for the vertex shader. So on each run of the shader, it will read a new value for both the vertex attribute and the color attribute.
As the fragment’s color eventually has to be set in the fragment shader and not in the vertex shader, we pass the color value over to it. To do this, we need to declare an equally named varying in both shaders. We called this varying varyingColor. If the fragment shader is now run for each fragment between the three vertices of a triangle, the value read by the shader is calculated by an interpolation of the three corners’ values. This means that if we specify the same color for the three vertices of a triangle, OpenGL will paint a plane colored triangle. If we specify different colors, OpenGL will smoothly blend between those values.
In the vertex shader’s main function, we only need to set the varying to the color value.
In the fragment shader’s main function, we set the gl_FragColor variable to the color received.
Of course we still need to use a new structure to store the color values and send them to the shaders in the QGLWidget::paintGL() method. But this should be very straightforward as we have already done all of this for the vertices attribute array in just the same manner.
There is only one little inconvenience when switching from a color uniform to a color attribute array. Unfortunately QGLShaderProgram::setAttributeArray() does not support the QColor type, so we need to store the colors as a QVector3D (or a QVector4D, if you want to set the alpha value to change the opacity). Valid color values range from 0 to 1. As we want to color each of the cube’s faces in a plain color, we set the color value of each face’s vertices to the same value.
Our cube now has its six sides colored differently.
Texture mapping is a very important concept in 3D computer graphics. It is the application of images on top of a model’s surfaces and is essential for creating a nice 3D scene.
You can do more with textures than just mapping them to a surface. Essentially a texture is a two dimensional array containing color values so not only can you pass colors to your shaders, but an array of any data you want. However, in this example we will use a classic 2D texture to map an image on top of the cube we created in the previous examples.

The source code related to this section is located in the examples/texture-mapping/ directory
In order to map a texture to a primitive, we have to specify so-called texture coordinates* that tell OpenGL which image coordinate is to be pinned to which vertex. Texture coordinates are instances of vec2 that are normalized to a range between 0 and 1. The origin of the texture coordinate system is in the lower left of an image, having the first axis pointing to the right side and the second axis pointing upwards (i.e. the lower left corner of an image is at (0, 0) and the upper right corner is at (1, 1)). Coordinate values higher than 1 are also allowed, causing the texture to wrap around by default.
The textures themselves are OpenGL objects stored in the graphics card’s memory. They are created using glGenTextures(GLsizei n, GLuint texture) and deleted again with a call to glDelereTextures(GLsizei n, const GLuint *texture). To identify textures, each texture is assigned a texture ID during its creation. As with shader programs, they must be bound to glBindTexture(GLenum target, GLuint texture) before they can be configured and filled with data. We can use Qt’s QGLWidget::bindTexture() to create the texture object. Normally we would have to make sure that the image data is in a particular format, according to the configuration of the texture object, but luckily QGLWidget::bindTexture() can take care of this.
OpenGL allows us to have several textures accessible to the shaders at the same time. For this purpose, OpenGL uses so-called texture units*. So before we can use a texture, we need to bind it to one of the texture units identified by the enum GL_TEXTUREi (with i ranging from 0 to GL_MAX_COMBINED_TEXTURE_UNITS -1). To do this, we call glActiveTexture(GLenum texture) and bind the texture using glBindTexture(GLenum target, GLuint texture). To add new textures or modify existing ones, we have to call glBindTexture(GLenum target, GLuint texture), overwrites the the current active texture unit. So you should set the active texture unit to an invalid unit after setting it by calling glActiveTexture(0). This way several texture units can be configured at the same time. Note that texture units must be used in an ascending order beginning with GL_TEXTURE0.
To access a texture in a shader to actually render it, we use the texture2D(sampler2D sampler, vec2 coord) function to query the color value at a certain texture coordinate. This function reads two parameters. The first parameter is of the type sampler2D and it refers to a texture unit. The second parameter is the texture coordinate that we want to access. To read from the texture unit i denoted by the enum GL_TEXTUREi, we have to pass the GLuint i as the uniform value.
With all of this theory we are now able to make our cube textured.
We replace the vec4 color attribute and the corresponding varying with a vec2 variable for the texture coordinates, and forward this value to the fragment shader.
In the fragment shader, we use texture2D(sampler2D sampler, vec2 coord) to look up the right color value. The uniform texture of the type sampler2D chooses the texture unit and we use the interpolated values coming from the vertex shader for the texture coordinates.
In the GlWidget class declaration, we replace the previously used colors member with a QVector made of QVector2Ds for the texture coordinates, and add a member variable to hold the texture object ID.
In the QGLWidget::initializeGL() reimplementation, we set up the texture coordinates and also create the texture object. Each side will be covered with the whole square image that is contained in our resource file.
In the QGLWidget::paintGL() method, we set the fragment shader’s sampler2D uniform to the first texture unit. Then we activate that unit, bind our texture object to it and after that deactivate it again to prevent us from accidentally overwriting this setting. And instead of passing the color attribute array, we pass the array containing the texture coordinates.
Our cube is now textured.
The Windows OpenGL header file only includes functionality up to OpenGL version 1.1 and assumes that the programmer will obtain additional functionality on his own. This includes OpenGL API function calls as well as enums. The reason is that, because different OpenGL libraries exist, the programmer should request the library’s function entry points at runtime.
Qt only defines the functionality required by its own OpenGL-related classes. glActiveTexture(GLenum texture) as well as the GL_TEXTUREi enums do not belong to this subset.
Several utility libraries exist to ease the definition of these functions (e.g. GLEW, GLEE, etc). We will define glActiveTexture(GLenum texture) and GL_TEXTUREi manually.
First we include the glext.h header file to set the missing enums and a few typedefs that help us make the code readable (as the version shipped with your compiler might be outdated, you may need to get the latest version from the OpenGL homepage). Next we declare the function pointer, which we will use to call glActiveTexture(GLenum texture) using the included typedefs. To avoid confusing the linker, we use a different name than glActiveTexture and define a pre-processor macro to replaces calls to glActiveTexture(GLenum texture) with our own function:
In the GlWidget::initializeGL() function, we request this pointer using PROC WINAPI wglGetProcAddress(LPCSTR lpszProc). This function reads the OpenGL API function’s name and returns a pointer which we need to cast to the right type:
glActiveTexture() and GL_TEXTUREi can then be used on Windows.
The ability to write your own shader programs gives you the power to set up the kind of lighting effect that best suits your needs. This may range from very basic and time saving approaches to high quality ray tracing algorithms.
In this chapter, we will implement a technique called Phong shading*, which is a popular baseline shading method for many rendering applications. For each pixel on the surface of an object, we will calculate the color intensity based on the position and color of the light source as well as the object’s texture and its material properties.
To show the results, we will display the cube with a light source circling above it. The light source will be marked by a pyramid, which we will render using the per-vertex color shader of one of the previous examples. So in this example, you will also see how to render a scene with multiple objects and different shader programs.

The source code related to this section is located in the examples/lighting/ directory
Because we use two different objects and two different shader programs, we added prefixes to the names. The cube is rendered using the lightingShaderProgram, for which we need an additional storage that keeps the surface normal of each vertex (i.e. the vector, that is perpendicular to the surface and has the size 1). The spotlight, on the other hand, is rendered using the coloringShaderProgram, which consists of a shader we developed earlier in this tutorial.
To track the position of the light source, we introduced a new member variable that holds its rotation. This value is periodically increased in the timeout() slot.
The Phong reflection model assumes that the light reflected off an object (i.e. what you actually see) consists of three components: diffuse reflection of rough surfaces, specular highlights of glossy surfaces, and an ambient term that sums up the small amounts of light that get scattered about the entire scene.
For each light source in the scene, we define i_d and i_s as the intensities (RGB values) of the diffuse and the specular components. i_a is defined as the ambient lighting component.
For each kind of surface (whether glossy or flat), we define the following parameters: k_d and k_s set the ratio of reflection of the diffuse and specular component, k_a sets the ratio of the reflection of the ambient term respectively and \alpha is a shininess constant that controls the size of the specular highlights.
The equation for computing the illumination of each surface point (fragment) is:

\hat
To obtain the vectors mentioned above, we calculate them for each vertex in the vertex shader and tell OpenGL to pass them as interpolated values to the fragment shader. In the fragment shader, we finally set the illumination of each point and combine it with the color value of the texture.
So in addition to passing vertex positions and the model-view-projection matrix to get the fragment's position, we also need to pass the surface normal of each vertex. To calculate the transformed cube's \hat
This is the vertex shader's source code:
The fragment shader is supplied with the light source's and the material's properties and the geometry data calculated by the vertex shader. It then sets the fragment's color value according to the above formula.
This is the fragment shaders source code:
In the GLWidget::initiliazeGL() method, we set up both shaders and prepare the attribute arrays of the cube and the spotlight. The only thing new here is the QVector made of QVector3Ds that stores the surface normal of each of the cube's vertices.
After clearing the screen and calculating the view matrix (which is the same for both objects) in the GlWidget::painGL() method, we first render the cube using the lighting shaders and then we render the spotlight using the coloring shader.
Because we want to keep the cube's origin aligned with the world's origin, we leave the model matrix (mMatrix) set to an identity matrix. Then we calculate the model-view matrix, which we also need to send to the lighting vertex shader, and extract the normal matrix with Qt's QMatrix4x4::normal() method. As we have already stated, this matrix will transform the surface normals of our cube from model coordinates into viewer coordinates. After that, we calculate the position of the light source in world coordinates according to the angle.
We can now render the cube. We bind the lighting shader program, set the uniforms and texture units, set and enable the attribute arrays, trigger the rendering, and afterwards disable the attribute arrays and release the program. For the light source's and the material's properties, we set values that give us a glossy looking surface.
Next we render the spotlight.
Because we want to move the spotlight to the same place as the light source, we need to modify its model matrix. First we restore the identity matrix (actually we did not modify the model matrix before so it still is set to the identity matrix anyway). Then we move the spotlight to the light sources position. Now we still want to rotate it as it looks nicer if it faces our cube. We therefore apply two rotation matrices on top. Because the pyramid that represents our lightspot is still too big to fit into our scene nicely, we scale it down to a tenth of its original size.
Now we follow the usual rendering procedure again, this time using the coloringShaderProgram and the spotlight data. Thanks to depth testing, the new object will be integrated seamlessly into our existing scene.
The last thing left to do is to initialize the light source's position and set up the timer. We tell the timer to periodically invoke the timout() slot.
In this slot we update the angle of the light source's circulation and update the screen. We also remove the calls to QGLWidget::updateGL() in the event handlers.
Now we are finished with the implementation. If you build and run the program, you will see a lit, textured cube.
Up till now, we have transferred all the objects' per-vertex data from the computer's RAM via the memory bus and the AGP bus to the graphics card whenever we wanted to re-render the scene. Obviously this is not very efficient and imposes a significant performance penalty - especially when handling large datasets. In this example, we will solve this problem by adding vertex buffer objects to the lighting example.
The source code related to this section is located in examples/buffer-objects/ directory
Buffer objects are general purpose arrays of data residing in the graphics card's memory. After we have allocated its space and filled it with data, we can repeatedly use it in different stages of the rendering pipeline. This means reading from and writing to it. We can also move this data around. All of these operations won't require anything from the CPU.
There are different types of buffer objects for different purposes. The most commonly used buffer object is the vertex buffer object, which serves as a source of vertex arrays.
In this example, we intend to use one vertex buffer per object (i.e. one vertex buffer for the cube and one vertex buffer for the spotlight), in which the attributes are densely packed next to each other in memory. We are not limited to using one single vertex buffer for all the attributes. Alternatively we could also use one vertex buffer for each vertex or a combination of both. Note that we can also mix the usage of vertex arrays and vertex buffers in one rendering.
Instead of using OpenGL API calls, we use the QGLBuffer class to manage the vertex buffers of the cube and the spotlight. The type of the buffer object can be set in the constructor. It defaults to being a vertex buffer.
We add a QGLBuffer member for each object, remove the vertex arrays we used in the previous version of the lighting example and add variables to hold the number of vertices, which will be necessary to tell OpenGL the number of vertices to render in the GlWidget::updateGL() method.
Buffer objects are OpenGL objects just like the shader programs and textures which we have already used in the preceding examples. So the syntax for handling them is quite similar.
In the GlWidget::initializeGL() method, we first need to create the buffer object. This is done by calling QGLBuffer::create(). It will request a free buffer object id (similar to a variable name) from the graphics card.
Then, as with textures, we need to bind it to the rendering context to make it active using QGLBuffer::bind().
After this, we call QGLBuffer::allocate() to allocate the amount of memory we need to store our vertices, normals, and texture coordinates. This function expects the number of bytes to reserve as a parameter. Using this method, we could also directly specify a pointer to the data which we want to be copied, but we want to arrange several datasets one after the other so we do the copying in the next few lines. Allocating memory also makes us responsible for freeing this space when it's not needed anymore by using QGLBuffer::destroy(). Qt will do this for us when the QGLBuffer object is destroyed.
Uploading data to the graphics card is done by using QGLBuffer::write(). It reads an offset (in bytes) from the beginning of the buffer object, a pointer to the data in the system memory, which is to be read from, and the number of bytes to copy. First we copy the cubes vertices. Then we append its surface normals and the texture coordinates. Note that because OpenGL uses GLfloats for its computations, we need to consider the size of the c
We do the same for the spotlight object.
Just in case you're interested, this is how the creation of buffer objects would work if we did not use Qt's QGLBuffer class for this purpose: We would call void glGenBuffers(GLsizei n, GLuint buffers) to request n numbers of buffer objects with their ids stored in buffers. Next we would bind the buffer using void glBindBuffer(enum target, uint bufferName), where we would also specify the buffer's type. Then we would use void glBufferData(enum target, sizeiptr size, const void *data, enum usage) to upload the data. The enum called usage specifies the way the buffer is used by the main program running on the CPU (for example, write-only, read-only, and copy-only) as well as the frequency of the buffer's usage, in order to support optimizations. void glDeleteBuffers(GLsizei n, const GLuint *buffers) is the OpenGL API function to delete buffers and free their memory.
To have OpenGL use our vertex buffer objects as the source of its vertex attributes, we need to set them differently in the GlWidget::updateGL() method.
Instead of calling QGLShaderProgram::setAttributeArray(), we need to call QGLShaderProgram::setAttributeBuffer() with the QGLBuffer instance bound to the rendering context. The parameters of QGLShaderProgram::setAttributeBuffer() are the same as those of QGLShaderProgram::setAttributeArray(). We only need to adapt the offset parameter to uniquely identify the location of the data because we now use one big chunk of memory for every attribute instead of one array for each of them.
Rendering the scene now involves less CPU usage and the attribute data is not repeatedly transferred from system memory to the graphics card anymore. Although this might not be visible in this small example, it certainly boosts up the speed of programs where more geometry data is involved.
QOpenGLWidget Class
QOpenGLWidget provides functionality for displaying OpenGL graphics integrated into a Qt application. It is very simple to use: Make your class inherit from it and use the subclass like any other QWidget, except that you have the choice between using QPainter and standard OpenGL rendering commands.
QOpenGLWidget provides three convenient virtual functions that you can reimplement in your subclass to perform the typical OpenGL tasks:
- paintGL() - Renders the OpenGL scene. Gets called whenever the widget needs to be updated.
- resizeGL() - Sets up the OpenGL viewport, projection, etc. Gets called whenever the widget has been resized (and also when it is shown for the first time because all newly created widgets get a resize event automatically).
- initializeGL() - Sets up the OpenGL resources and state. Gets called once before the first time resizeGL() or paintGL() is called.
If you need to trigger a repaint from places other than paintGL() (a typical example is when using timers to animate scenes), you should call the widget's update() function to schedule an update.
Your widget's OpenGL rendering context is made current when paintGL(), resizeGL(), or initializeGL() is called. If you need to call the standard OpenGL API functions from other places (e.g. in your widget's constructor or in your own paint functions), you must call makeCurrent() first.
All rendering happens into an OpenGL framebuffer object. makeCurrent() ensure that it is bound in the context. Keep this in mind when creating and binding additional framebuffer objects in the rendering code in paintGL(). Never re-bind the framebuffer with ID 0. Instead, call defaultFramebufferObject() to get the ID that should be bound.
QOpenGLWidget allows using different OpenGL versions and profiles when the platform supports it. Just set the requested format via setFormat(). Keep in mind however that having multiple QOpenGLWidget instances in the same window requires that they all use the same format, or at least formats that do not make the contexts non-sharable. To overcome this issue, prefer using QSurfaceFormat::setDefaultFormat() instead of setFormat().
Note: Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory on some platforms (for example, macOS) when an OpenGL core profile context is requested. This is to ensure that resource sharing between contexts stays functional as all internal contexts are created using the correct version and profile.
Painting Techniques
As described above, subclass QOpenGLWidget to render pure 3D content in the following way:
- Reimplement the initializeGL() and resizeGL() functions to set up the OpenGL state and provide a perspective transformation.
- Reimplement paintGL() to paint the 3D scene, calling only OpenGL functions.
It is also possible to draw 2D graphics onto a QOpenGLWidget subclass using QPainter:
- In paintGL(), instead of issuing OpenGL commands, construct a QPainter object for use on the widget.
- Draw primitives using QPainter's member functions.
- Direct OpenGL commands can still be issued. However, you must make sure these are enclosed by a call to the painter's beginNativePainting() and endNativePainting().
When performing drawing using QPainter only, it is also possible to perform the painting like it is done for ordinary widgets: by reimplementing paintEvent().
- Reimplement the paintEvent() function.
- Construct a QPainter object targeting the widget. Either pass the widget to the constructor or the QPainter::begin() function.
- Draw primitives using QPainter's member functions.
- Painting finishes then the QPainter instance is destroyed. Alternatively, call QPainter::end() explicitly.
OpenGL Function Calls, Headers and QOpenGLFunctions
When making OpenGL function calls, it is strongly recommended to avoid calling the functions directly. Instead, prefer using QOpenGLFunctions (when making portable applications) or the versioned variants (for example, QOpenGLFunctions_3_2_Core and similar, when targeting modern, desktop-only OpenGL). This way the application will work correctly in all Qt build configurations, including the ones that perform dynamic OpenGL implementation loading which means applications are not directly linking to an GL implementation and thus direct function calls are not feasible.
In paintGL() the current context is always accessible by caling QOpenGLContext::currentContext(). From this context an already initialized, ready-to-be-used QOpenGLFunctions instance is retrievable by calling QOpenGLContext::functions(). An alternative to prefixing every GL call is to inherit from QOpenGLFunctions and call QOpenGLFunctions::initializeOpenGLFunctions() in initializeGL().
As for the OpenGL headers, note that in most cases there will be no need to directly include any headers like GL.h. The OpenGL-related Qt headers will include qopengl.h which will in turn include an appropriate header for the system. This might be an OpenGL ES 3.x or 2.0 header, the highest version that is available, or a system-provided gl.h. In addition, a copy of the extension headers (called glext.h on some systems) is provided as part of Qt both for OpenGL and OpenGL ES. These will get included automatically on platforms where feasible. This means that constants and function pointer typedefs from ARB, EXT, OES extensions are automatically available.
Code Examples
To get started, the simplest QOpenGLWidget subclass could like like the following:
Alternatively, the prefixing of each and every OpenGL call can be avoided by deriving from QOpenGLFunctions instead:
To get a context compatible with a given OpenGL version or profile, or to request depth and stencil buffers, call setFormat():
With OpenGL 3.0+ contexts, when portability is not important, the versioned QOpenGLFunctions variants give easy access to all the modern OpenGL functions available in a given version:
As described above, it is simpler and more robust to set the requested format globally so that it applies to all windows and contexts during the lifetime of the application. Below is an example of this:
Multisampling
To enable multisampling, set the number of requested samples on the QSurfaceFormat that is passed to setFormat(). On systems that do not support it the request may get ignored.
Multisampling support requires support for multisampled renderbuffers and framebuffer blits. On OpenGL ES 2.0 implementations it is likely that these will not be present. This means that multisampling will not be available. With modern OpenGL versions and OpenGL ES 3.0 and up this is usually not a problem anymore.
Threading
Performing offscreen rendering on worker threads, for example to generate textures that are then used in the GUI/main thread in paintGL(), are supported by exposing the widget's QOpenGLContext so that additional contexts sharing with it can be created on each thread.
Drawing directly to the QOpenGLWidget's framebuffer outside the GUI/main thread is possible by reimplementing paintEvent() to do nothing. The context's thread affinity has to be changed via QObject::moveToThread(). After that, makeCurrent() and doneCurrent() are usable on the worker thread. Be careful to move the context back to the GUI/main thread afterwards.
Triggering a buffer swap just for the QOpenGLWidget is not possible since there is no real, onscreen native surface for it. It is up to the widget stack to manage composition and buffer swaps on the gui thread. When a thread is done updating the framebuffer, call update() on the GUI/main thread to schedule composition.
Extra care has to be taken to avoid using the framebuffer when the GUI/main thread is performing compositing. The signals aboutToCompose() and frameSwapped() will be emitted when the composition is starting and ending. They are emitted on the GUI/main thread. This means that by using a direct connection aboutToCompose() can block the GUI/main thread until the worker thread has finished its rendering. After that, the worker thread must perform no further rendering until the frameSwapped() signal is emitted. If this is not acceptable, the worker thread has to implement a double buffering mechanism. This involves drawing using an alternative render target, that is fully controlled by the thread, e.g. an additional framebuffer object, and blitting to the QOpenGLWidget's framebuffer at a suitable time.
Context Sharing
When multiple QOpenGLWidgets are added as children to the same top-level widget, their contexts will share with each other. This does not apply for QOpenGLWidget instances that belong to different windows.
This means that all QOpenGLWidgets in the same window can access each other's sharable resources, like textures, and there is no need for an extra "global share" context.
To set up sharing between QOpenGLWidget instances belonging to different windows, set the Qt::AA_ShareOpenGLContexts application attribute before instantiating QApplication. This will trigger sharing between all QOpenGLWidget instances without any further steps.
Creating extra QOpenGLContext instances that share resources like textures with the QOpenGLWidget's context is also possible. Simply pass the pointer returned from context() to QOpenGLContext::setShareContext() before calling QOpenGLContext::create(). The resulting context can also be used on a different thread, allowing threaded generation of textures and asynchronous texture uploads.
Note that QOpenGLWidget expects a standard conformant implementation of resource sharing when it comes to the underlying graphics drivers. For example, some drivers, in particular for mobile and embedded hardware, have issues with setting up sharing between an existing context and others that are created later. Some other drivers may behave in unexpected ways when trying to utilize shared resources between different threads.
Resource Initialization and Cleanup
The QOpenGLWidget's associated OpenGL context is guaranteed to be current whenever initializeGL() and paintGL() are invoked. Do not attempt to create OpenGL resources before initializeGL() is called. For example, attempting to compile shaders, initialize vertex buffer objects or upload texture data will fail when done in a subclass's constructor. These operations must be deferred to initializeGL(). Some of Qt's OpenGL helper classes, like QOpenGLBuffer or QOpenGLVertexArrayObject, have a matching deferred behavior: they can be instantiated without a context, but all initialization is deferred until a create(), or similar, call. This means that they can be used as normal (non-pointer) member variables in a QOpenGLWidget subclass, but the create() or similar function can only be called from initializeGL(). Be aware however that not all classes are designed like this. When in doubt, make the member variable a pointer and create and destroy the instance dynamically in initializeGL() and the destructor, respectively.
Releasing the resources also needs the context to be current. Therefore destructors that perform such cleanup are expected to call makeCurrent() before moving on to destroy any OpenGL resources or wrappers. Avoid deferred deletion via deleteLater() or the parenting mechanism of QObject. There is no guarantee the correct context will be current at the time the instance in question is really destroyed.
A typical subclass will therefore often look like the following when it comes to resource initialization and destruction:
This is naturally not the only possible solution. One alternative is to use the aboutToBeDestroyed() signal of QOpenGLContext. By connecting a slot, using direct connection, to this signal, it is possible to perform cleanup whenever the underlying native context handle, or the entire QOpenGLContext instance, is going to be released. The following snippet is in principle equivalent to the previous one:
Note: For widgets that change their associated top-level window multiple times during their lifetime, a combined approach is essential. Whenever the widget or a parent of it gets reparented so that the top-level window becomes different, the widget's associated context is destroyed and a new one is created. This is then followed by a call to initializeGL() where all OpenGL resources must get reinitialized. Due to this the only option to perform proper cleanup is to connect to the context's aboutToBeDestroyed() signal. Note that the context in question may not be the current one when the signal gets emitted. Therefore it is good practice to call makeCurrent() in the connected slot. Additionally, the same cleanup steps must be performed from the derived class' destructor, since the slot connected to the signal will not get invoked when the widget is being destroyed.
Note: When Qt::AA_ShareOpenGLContexts is set, the widget's context never changes, not even when reparenting because the widget's associated texture is guaranteed to be accessible also from the new top-level's context.
Proper cleanup is especially important due to context sharing. Even though each QOpenGLWidget's associated context is destroyed together with the QOpenGLWidget, the sharable resources in that context, like textures, will stay valid until the top-level window, in which the QOpenGLWidget lived, is destroyed. Additionally, settings like Qt::AA_ShareOpenGLContexts and some Qt modules may trigger an even wider scope for sharing contexts, potentially leading to keeping the resources in question alive for the entire lifetime of the application. Therefore the safest and most robust is always to perform explicit cleanup for all resources and resource wrappers used in the QOpenGLWidget.
Limitations
Putting other widgets underneath and making the QOpenGLWidget transparent will not lead to the expected results: The widgets underneath will not be visible. This is because in practice the QOpenGLWidget is drawn before all other regular, non-OpenGL widgets, and so see-through type of solutions are not feasible. Other type of layouts, like having widgets on top of the QOpenGLWidget, will function as expected.
When absolutely necessary, this limitation can be overcome by setting the Qt::WA_AlwaysStackOnTop attribute on the QOpenGLWidget. Be aware however that this breaks stacking order, for example it will not be possible to have other widgets on top of the QOpenGLWidget, so it should only be used in situations where a semi-transparent QOpenGLWidget with other widgets visible underneath is required.
Note that this does not apply when there are no other widgets underneath and the intention is to have a semi-transparent window. In that case the traditional approach of setting Qt::WA_TranslucentBackground on the top-level window is sufficient. Note that if the transparent areas are only desired in the QOpenGLWidget, then Qt::WA_NoSystemBackground will need to be turned back to false after enabling Qt::WA_TranslucentBackground. Additionally, requesting an alpha channel for the QOpenGLWidget's context via setFormat() may be necessary too, depending on the system.
QOpenGLWidget supports multiple update behaviors, just like QOpenGLWindow. In preserved mode the rendered content from the previous paintGL() call is available in the next one, allowing incremental rendering. In non-preserved mode the content is lost and paintGL() implementations are expected to redraw everything in the view.
Before Qt 5.5 the default behavior of QOpenGLWidget was to preserve the rendered contents between paintGL() calls. Since Qt 5.5 the default behavior is non-preserved because this provides better performance and the majority of applications have no need for the previous content. This also resembles the semantics of an OpenGL-based QWindow and matches the default behavior of QOpenGLWindow in that the color and ancillary buffers are invalidated for each frame. To restore the preserved behavior, call setUpdateBehavior() with PartialUpdate .
Note: Displaying a QOpenGLWidget requires an alpha channel in the associated top-level window's backing store due to the way composition with other QWidget-based content works. If there is no alpha channel, the content rendered by the QOpenGLWidget will not be visible. This can become particularly relevant on Linux/X11 in remote display setups (such as, with Xvnc), when using a color depth lower than 24. For example, a color depth of 16 will typically map to using a backing store image with the format QImage::Format_RGB16 (RGB565), leaving no room for an alpha channel. Therefore, if experiencing problems with getting the contents of a QOpenGLWidget composited correctly with other the widgets in the window, make sure the server (such as, vncserver) is configured with a 24 or 32 bit depth instead of 16.
Alternatives
Adding a QOpenGLWidget into a window turns on OpenGL-based compositing for the entire window. In some special cases this may not be ideal, and the old QGLWidget-style behavior with a separate, native child window is desired. Desktop applications that understand the limitations of this approach (for example when it comes to overlaps, transparency, scroll views and MDI areas), can use QOpenGLWindow with QWidget::createWindowContainer(). This is a modern alternative to QGLWidget and is faster than QOpenGLWidget due to the lack of the additional composition step. It is strongly recommended to limit the usage of this approach to cases where there is no other choice. Note that this option is not suitable for most embedded and mobile platforms, and it is known to have issues on certain desktop platforms (e.g. macOS) too. The stable, cross-platform solution is always QOpenGLWidget.
OpenGL is a trademark of Silicon Graphics, Inc. in the United States and other countries.
Member Type Documentation
[since 5.5] enum QOpenGLWidget:: UpdateBehavior
This enum describes the update semantics of QOpenGLWidget.
| Constant | Value | Description |
|---|---|---|
| QOpenGLWidget::NoPartialUpdate | 0 | QOpenGLWidget will discard the contents of the color buffer and the ancillary buffers after the QOpenGLWidget is rendered to screen. This is the same behavior that can be expected by calling QOpenGLContext::swapBuffers with a default opengl enabled QWindow as the argument. NoPartialUpdate can have some performance benefits on certain hardware architectures common in the mobile and embedded space when a framebuffer object is used as the rendering target. The framebuffer object is invalidated between frames with glDiscardFramebufferEXT if supported or a glClear. Please see the documentation of EXT_discard_framebuffer for more information: https://www.khronos.org/registry/gles/extensions/EXT/EXT_discard_framebuffer.txt |
| QOpenGLWidget::PartialUpdate | 1 | The framebuffer objects color buffer and ancillary buffers are not invalidated between frames. |
This enum was introduced or modified in Qt 5.5.
Member Function Documentation
QOpenGLWidget:: QOpenGLWidget ( QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags())
Constructs a widget which is a child of parent, with widget flags set to f.
[signal] void QOpenGLWidget:: aboutToCompose ()
This signal is emitted when the widget's top-level window is about to begin composing the textures of its QOpenGLWidget children and the other widgets.
[signal] void QOpenGLWidget:: aboutToResize ()
This signal is emitted when the widget's size is changed and therefore the framebuffer object is going to be recreated.
[signal] void QOpenGLWidget:: frameSwapped ()
This signal is emitted after the widget's top-level window has finished composition and returned from its potentially blocking QOpenGLContext::swapBuffers() call.
[signal] void QOpenGLWidget:: resized ()
This signal is emitted right after the framebuffer object has been recreated due to resizing the widget.
[virtual] QOpenGLWidget::
Destroys the QOpenGLWidget instance, freeing its resources.
The QOpenGLWidget's context is made current in the destructor, allowing for safe destruction of any child object that may need to release OpenGL resources belonging to the context provided by this widget.
Warning: if you have objects wrapping OpenGL resources (such as QOpenGLBuffer, QOpenGLShaderProgram, etc.) as members of a OpenGLWidget subclass, you may need to add a call to makeCurrent() in that subclass' destructor as well. Due to the rules of C++ object destruction, those objects will be destroyed before calling this function (but after that the destructor of the subclass has run), therefore making the OpenGL context current in this function happens too late for their safe disposal.
QOpenGLContext *QOpenGLWidget:: context () const
Returns The QOpenGLContext used by this widget or 0 if not yet initialized.
Note: The context and the framebuffer object used by the widget changes when reparenting the widget via setParent().
GLuint QOpenGLWidget:: defaultFramebufferObject () const
Returns The framebuffer object handle or 0 if not yet initialized.
Note: The framebuffer object belongs to the context returned by context() and may not be accessible from other contexts.
Note: The context and the framebuffer object used by the widget changes when reparenting the widget via setParent(). In addition, the framebuffer object changes on each resize.
void QOpenGLWidget:: doneCurrent ()
Releases the context.
It is not necessary to call this function in most cases, since the widget will make sure the context is bound and released properly when invoking paintGL().
[override virtual protected] bool QOpenGLWidget:: event ( QEvent *e)
Reimplements: QWidget::event(QEvent *event).
QSurfaceFormat QOpenGLWidget:: format () const
Returns the context and surface format used by this widget and its toplevel window.
After the widget and its toplevel have both been created, resized and shown, this function will return the actual format of the context. This may differ from the requested format if the request could not be fulfilled by the platform. It is also possible to get larger color buffer sizes than requested.
When the widget's window and the related OpenGL resources are not yet initialized, the return value is the format that has been set via setFormat().
QImage QOpenGLWidget:: grabFramebuffer ()
Renders and returns a 32-bit RGB image of the framebuffer.
Note: This is a potentially expensive operation because it relies on glReadPixels() to read back the pixels. This may be slow and can stall the GPU pipeline.
[virtual protected] void QOpenGLWidget:: initializeGL ()
This virtual function is called once before the first call to paintGL() or resizeGL(). Reimplement it in a subclass.
This function should set up any required OpenGL resources and state.
There is no need to call makeCurrent() because this has already been done when this function is called. Note however that the framebuffer is not yet available at this stage, so avoid issuing draw calls from here. Defer such calls to paintGL() instead.
bool QOpenGLWidget:: isValid () const
Returns true if the widget and OpenGL resources, like the context, have been successfully initialized. Note that the return value is always false until the widget is shown.
void QOpenGLWidget:: makeCurrent ()
Prepares for rendering OpenGL content for this widget by making the corresponding context current and binding the framebuffer object in that context.
It is not necessary to call this function in most cases, because it is called automatically before invoking paintGL().
[override virtual protected] int QOpenGLWidget:: metric ( QPaintDevice::PaintDeviceMetric metric) const
[override virtual protected] QPaintEngine *QOpenGLWidget:: paintEngine () const
[override virtual protected] void QOpenGLWidget:: paintEvent ( QPaintEvent *e)
Reimplements: QWidget::paintEvent(QPaintEvent *event).
Handles paint events.
Calling QWidget::update() will lead to sending a paint event e, and thus invoking this function. (NB this is asynchronous and will happen at some point after returning from update()). This function will then, after some preparation, call the virtual paintGL() to update the contents of the QOpenGLWidget's framebuffer. The widget's top-level window will then composite the framebuffer's texture with the rest of the window.
[virtual protected] void QOpenGLWidget:: paintGL ()
This virtual function is called whenever the widget needs to be painted. Reimplement it in a subclass.
There is no need to call makeCurrent() because this has already been done when this function is called.
Before invoking this function, the context and the framebuffer are bound, and the viewport is set up by a call to glViewport(). No other state is set and no clearing or drawing is performed by the framework.
[override virtual protected] QPaintDevice *QOpenGLWidget:: redirected ( QPoint *p) const
[override virtual protected] void QOpenGLWidget:: resizeEvent ( QResizeEvent *e)
Reimplements: QWidget::resizeEvent(QResizeEvent *event).
Handles resize events that are passed in the e event parameter. Calls the virtual function resizeGL().
Note: Avoid overriding this function in derived classes. If that is not feasible, make sure that QOpenGLWidget's implementation is invoked too. Otherwise the underlying framebuffer object and related resources will not get resized properly and will lead to incorrect rendering.
[virtual protected] void QOpenGLWidget:: resizeGL ( int w, int h)
This virtual function is called whenever the widget has been resized. Reimplement it in a subclass. The new size is passed in w and h.
There is no need to call makeCurrent() because this has already been done when this function is called. Additionally, the framebuffer is also bound.
void QOpenGLWidget:: setFormat (const QSurfaceFormat &format)
Sets the requested surface format.
When the format is not explicitly set via this function, the format returned by QSurfaceFormat::defaultFormat() will be used. This means that when having multiple OpenGL widgets, individual calls to this function can be replaced by one single call to QSurfaceFormat::setDefaultFormat() before creating the first widget.
Note: Requesting an alpha buffer via this function will not lead to the desired results when the intention is to make other widgets beneath visible. Instead, use Qt::WA_AlwaysStackOnTop to enable semi-transparent QOpenGLWidget instances with other widgets visible underneath. Keep in mind however that this breaks the stacking order, so it will no longer be possible to have other widgets on top of the QOpenGLWidget.
[since 5.10] void QOpenGLWidget:: setTextureFormat ( GLenum texFormat)
Sets a custom internal texture format of texFormat.
When working with sRGB framebuffers, it will be necessary to specify a format like GL_SRGB8_ALPHA8 . This can be achieved by calling this function.
Note: This function has no effect if called after the widget has already been shown and thus it performed initialization.
Note: This function will typically have to be used in combination with a QSurfaceFormat::setDefaultFormat() call that sets the color space to QSurfaceFormat::sRGBColorSpace.
This function was introduced in Qt 5.10.
[since 5.5] void QOpenGLWidget:: setUpdateBehavior ( QOpenGLWidget::UpdateBehavior updateBehavior)
Sets this widget's update behavior to updateBehavior.
This function was introduced in Qt 5.5.
[since 5.10] GLenum QOpenGLWidget:: textureFormat () const
Returns the active internal texture format if the widget has already initialized, the requested format if one was set but the widget has not yet been made visible, or nullptr if setTextureFormat() was not called and the widget has not yet been made visible.