MyGLWidget::~MyGLWidget()
cleanup();
void MyGLWidget::initializeGL()
...
connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &MyGLWidget::cleanup);
void MyGLWidget::cleanup()
makeCurrent();
delete m_texture;
m_texture = 0;
...
doneCurrent();
disconnect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &MyGLWidget::cleanup);
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.
Stereoscopic rendering
Starting from 6.5 QOpenGLWidget has support for stereoscopic rendering. To enable it, set the QSurfaceFormat::StereoBuffers flag globally before the window is created, using QSurfaceFormat::SetDefaultFormat().
Note: Using setFormat() will not necessarily work because of how the flag is handled internally.
This will trigger paintGL() to be called twice each frame, once for each QOpenGLWidget::TargetBuffer. In paintGL(), call currentTargetBuffer() to query which one is currently being drawn to.
Note: For more control over the left and right color buffers, consider using QOpenGLWindow + QWidget::createWindowContainer() instead.
Note: This type of 3D rendering has certain hardware requirements, like the graphics card needs to be setup with stereo support.
OpenGL is a trademark of Silicon Graphics, Inc. in the United States and other countries.
See also QOpenGLFunctions, QOpenGLWindow, Qt::AA_ShareOpenGLContexts, and UpdateBehavior.
Member Type Documentation
[since 6.5]
enum QOpenGLWidget::TargetBuffer
Specifies the buffer to use when stereoscopic rendering is enabled, which is toggled by setting QSurfaceFormat::StereoBuffers.
Note: LeftBuffer is always the default and used as fallback value when stereoscopic rendering is disabled or not supported by the graphics driver.
This enum was introduced in Qt 6.5.
enum QOpenGLWidget::UpdateBehavior
This enum describes the update semantics of QOpenGLWidget.
Constant | Value |
QOpenGLWidget::LeftBuffer | 0 |
QOpenGLWidget::RightBuffer | 1 |
See also updateBehavior() and setUpdateBehavior().
Member Function Documentation
Constructs a widget which is a child of parent, with widget flags set to f.
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.
See also makeCurrent.
[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.
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().
See also QOpenGLContext::setShareContext() and defaultFramebufferObject().
[since 6.5]
QOpenGLWidget::TargetBuffer QOpenGLWidget::currentTargetBuffer() const
Returns the currently active target buffer. This will be the left buffer by default, the right buffer is only used when QSurfaceFormat::StereoBuffers is enabled. When stereoscopic rendering is enabled, this can be queried in paintGL() to know what buffer is currently in use. paintGL() will be called twice, once for each target.
This function was introduced in Qt 6.5.
See also paintGL().
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.
See also context().
[since 6.5]
GLuint QOpenGLWidget::defaultFramebufferObject(QOpenGLWidget::TargetBuffer targetBuffer) const
Returns The framebuffer object handle of the specified target buffer or 0
if not yet initialized.
Calling this overload only makes sense if QSurfaceFormat::StereoBuffers is enabled and supported by the hardware. If not, this method will return the default buffer.
Note: The framebuffer object belongs to the context returned by context() and may not be accessible from other contexts. 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.
This function was introduced in Qt 6.5.
See also context().
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).
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().
See also setFormat() and context().
[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.
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.
Renders and returns a 32-bit RGB image of the framebuffer of the specified target buffer. This overload only makes sense to call when QSurfaceFormat::StereoBuffers is enabled. Grabbing the framebuffer of the right target buffer will return the default image if stereoscopic rendering is disabled or if not supported by the hardware.
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.
This function was introduced in Qt 6.5.
[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.
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.
See also paintGL() and resizeGL().
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.
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().
See also context(), paintGL(), and doneCurrent().
[since 6.5]
void QOpenGLWidget::makeCurrent(QOpenGLWidget::TargetBuffer targetBuffer)
Prepares for rendering OpenGL content for this widget by making the context for the passed in buffer current and binding the framebuffer object in that context.
Note: This only makes sense to call when stereoscopic rendering is enabled. Nothing will happen if the right buffer is requested when it's disabled.
It is not necessary to call this function in most cases, because it is called automatically before invoking paintGL().
This function was introduced in Qt 6.5.
See also context(), paintGL(), and doneCurrent().
[override virtual protected]
int QOpenGLWidget::metric(QPaintDevice::PaintDeviceMetric metric) const
Reimplements: QWidget::metric(QPaintDevice::PaintDeviceMetric m) const.
[override virtual protected]
QPaintEngine *QOpenGLWidget::paintEngine() const
Reimplements: QWidget::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.
Note: To ensure portability, do not expect that state set in initializeGL() persists. Rather, set all necessary state, for example, by calling glEnable(), in paintGL(). This is because some platforms, such as WebAssembly with WebGL, may have limitations on OpenGL contexts in some situations, which can lead to using the context used with the QOpenGLWidget for other purposes as well.
When QSurfaceFormat::StereoBuffers is enabled, this function will be called twice - once for each buffer. Query what buffer is currently bound by calling currentTargetBuffer().
Note: The framebuffer of each target will be drawn to even when stereoscopic rendering is not supported by the hardware. Only the left buffer will actually be visible in the window.
See also initializeGL(), resizeGL(), and currentTargetBuffer().
[override virtual protected]
QPaintDevice *QOpenGLWidget::redirected(QPoint *p) const
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.
See also initializeGL() and paintGL().
[signal]
void QOpenGLWidget::resized()
This signal is emitted right after the framebuffer object has been recreated due to resizing the widget.
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.
See also format(), Qt::WA_AlwaysStackOnTop, and QSurfaceFormat::setDefaultFormat().
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.
See also textureFormat().
Sets this widget's update behavior to updateBehavior.
See also updateBehavior().
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.
See also setTextureFormat().
Returns the update behavior of the widget.
See also setUpdateBehavior().
© 2024 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.
Detailed Description
Painting Techniques
OpenGL Function Calls, Headers and QOpenGLFunctions
Code Examples
Multisampling
Threading
Context Sharing
Resource Initialization and Cleanup
Limitations and Other Considerations
Alternatives
Stereoscopic rendering
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. |