- class QOpenGLWidget#
The
QOpenGLWidget
class is a widget for rendering OpenGL graphics. More…Synopsis#
Methods#
def
__init__()
def
context()
def
doneCurrent()
def
format()
def
isValid()
def
makeCurrent()
def
setFormat()
def
textureFormat()
def
updateBehavior()
Virtual methods#
def
initializeGL()
def
paintGL()
def
resizeGL()
Signals#
def
aboutToCompose()
def
aboutToResize()
def
frameSwapped()
def
resized()
Note
This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE
Detailed Description#
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
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 timeresizeGL()
orpaintGL()
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()
, orinitializeGL()
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 callmakeCurrent()
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 inpaintGL()
. Never re-bind the framebuffer with ID 0. Instead, calldefaultFramebufferObject()
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 viasetFormat()
. Keep in mind however that having multipleQOpenGLWidget
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 ofsetFormat()
.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()
andresizeGL()
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() ininitializeGL()
.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:class MyGLWidget(QOpenGLWidget): # public MyGLWidget(QWidget parent) : QOpenGLWidget(parent) { } # protected def initializeGL(): # Set up the rendering context, load shaders and other resources, etc.: f = QOpenGLContext.currentContext().functions() f.glClearColor(1.0f, 1.0f, 1.0f, 1.0f) ... def resizeGL(w, h): # Update projection matrix and other size related settings: m_projection.setToIdentity() m_projection.perspective(45.0f, w / float(h), 0.01f, 100.0f) ... def paintGL(): # Draw the scene: f = QOpenGLContext.currentContext().functions() f.glClear(GL_COLOR_BUFFER_BIT) ...
Alternatively, the prefixing of each and every OpenGL call can be avoided by deriving from QOpenGLFunctions instead:
class MyGLWidget(QOpenGLWidget, QOpenGLFunctions): ... def initializeGL(): initializeOpenGLFunctions() glClearColor(...) ... ...
To get a context compatible with a given OpenGL version or profile, or to request depth and stencil buffers, call
setFormat()
:widget = QOpenGLWidget(parent) format = QSurfaceFormat() format.setDepthBufferSize(24) format.setStencilBufferSize(8) format.setVersion(3, 2) format.setProfile(QSurfaceFormat.CoreProfile) widget.setFormat(format) # must be called before the widget or its parent window gets shown
Note
It is up to the application to ensure depth and stencil buffers are requested from the underlying windowing system interface. Without requesting a non-zero depth buffer size there is no guarantee that a depth buffer will be available, and as a result depth testing related OpenGL operations may fail to function as expected. Commonly used depth and stencil buffer size requests are 24 and 8, respectively.
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:
... def paintGL(): QOpenGLFunctions_3_2_Core f = QOpenGLContext.currentContext().versionFunctions<QOpenGLFunctions_3_2_Core>() ... f.glDrawArraysInstanced(...) ... ...
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:
if __name__ == "__main__": app = QApplication([]) format = QSurfaceFormat() format.setDepthBufferSize(24) format.setStencilBufferSize(8) format.setVersion(3, 2) format.setProfile(QSurfaceFormat.CoreProfile) QSurfaceFormat.setDefaultFormat(format) widget = MyWidget() widget.show() sys.exit(app.exec())
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 reimplementingpaintEvent()
to do nothing. The context’s thread affinity has to be changed via QObject::moveToThread(). After that,makeCurrent()
anddoneCurrent()
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()
andframeSwapped()
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 connectionaboutToCompose()
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 theframeSwapped()
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 theQOpenGLWidget
‘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 allQOpenGLWidget
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 fromcontext()
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 wheneverinitializeGL()
andpaintGL()
are invoked. Do not attempt to create OpenGL resources beforeinitializeGL()
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 toinitializeGL()
. Some of Qt’s OpenGL helper classes, likeQOpenGLBuffer
orQOpenGLVertexArrayObject
, 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 aQOpenGLWidget
subclass, but the create() or similar function can only be called frominitializeGL()
. 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 ininitializeGL()
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:
class MyGLWidget(QOpenGLWidget): ... # private m_vao = QOpenGLVertexArrayObject() m_vbo = QOpenGLBuffer() m_program = QOpenGLShaderProgram() m_shader = QOpenGLShader() m_texture = QOpenGLTexture() def __init__(self): self.m_program = 0 self.m_shader = 0 self.m_texture = 0 # No OpenGL resource initialization is done here. MyGLWidget.~MyGLWidget() # Make sure the context is current and then explicitly # destroy all underlying OpenGL resources. makeCurrent() del m_texture del m_shader del m_program m_vbo.destroy() m_vao.destroy() doneCurrent() def initializeGL(self): m_vao.create() if m_vao.isCreated(): m_vao.bind() m_vbo.create() m_vbo.bind() m_vbo.allocate(...) m_texture = QOpenGLTexture(QImage(...)) m_shader = QOpenGLShader(...) m_program = QOpenGLShaderProgram(...) ...
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 callmakeCurrent()
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.MyGLWidget.~MyGLWidget() cleanup() def initializeGL(self): ... connect(context(), &QOpenGLContext::aboutToBeDestroyed, self.cleanup) def cleanup(self): makeCurrent() del m_texture m_texture = 0 ... doneCurrent() disconnect(context(), &QOpenGLContext::aboutToBeDestroyed, self.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 theQOpenGLWidget
, the sharable resources in that context, like textures, will stay valid until the top-level window, in which theQOpenGLWidget
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 theQOpenGLWidget
.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 theQOpenGLWidget
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 theQOpenGLWidget
, 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 theQOpenGLWidget
, so it should only be used in situations where a semi-transparentQOpenGLWidget
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 tofalse
after enabling Qt::WA_TranslucentBackground. Additionally, requesting an alpha channel for theQOpenGLWidget
‘s context viasetFormat()
may be necessary too, depending on the system.QOpenGLWidget
supports multiple update behaviors, just likeQOpenGLWindow
. In preserved mode the rendered content from the previouspaintGL()
call is available in the next one, allowing incremental rendering. In non-preserved mode the content is lost andpaintGL()
implementations are expected to redraw everything in the view.Before Qt 5.5 the default behavior of
QOpenGLWidget
was to preserve the rendered contents betweenpaintGL()
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 ofQOpenGLWindow
in that the color and ancillary buffers are invalidated for each frame. To restore the preserved behavior, callsetUpdateBehavior()
withPartialUpdate
.Note
When dynamically adding a
QOpenGLWidget
into a widget hierarchy, e.g. by parenting a newQOpenGLWidget
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 theQOpenGLWidget
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 theQOpenGLWidget
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 theQOpenGLWidget
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 aQOpenGLWidget
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 useQOpenGLWindow
with QWidget::createWindowContainer(). This is a modern alternative to QGLWidget and is faster thanQOpenGLWidget
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 alwaysQOpenGLWidget
.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 eachTargetBuffer
. InpaintGL()
, callcurrentTargetBuffer()
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
- class UpdateBehavior#
This enum describes the update semantics of
QOpenGLWidget
.Constant
Description
QOpenGLWidget.NoPartialUpdate
QOpenGLWidget
will discard the contents of the color buffer and the ancillary buffers after theQOpenGLWidget
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 glInvalidateFramebuffer (if supported), or, as fallbacks, glDiscardFramebufferEXT (if supported) or a call to glClear.QOpenGLWidget.PartialUpdate
The framebuffer objects color buffer and ancillary buffers are not invalidated between frames.
See also
- class 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.
Constant
Description
QOpenGLWidget.LeftBuffer
QOpenGLWidget.RightBuffer
New in version 6.5.
- __init__([parent=None[, f=Qt.WindowFlags()]])#
- Parameters:
parent –
QWidget
f – Combination of
WindowType
Constructs a widget which is a child of
parent
, with widget flags set tof
.- 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.- aboutToResize()#
This signal is emitted when the widget’s size is changed and therefore the framebuffer object is going to be recreated.
- context()#
- Return type:
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
- currentTargetBuffer()#
- Return type:
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.See also
- defaultFramebufferObject()#
- Return type:
int
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
- defaultFramebufferObject(targetBuffer)
- Parameters:
targetBuffer –
TargetBuffer
- Return type:
int
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.See also
- 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()
.- format()#
- Return type:
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
- frameSwapped()#
This signal is emitted after the widget’s top-level window has finished composition and returned from its potentially blocking QOpenGLContext::swapBuffers() call.
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.
- grabFramebuffer(targetBuffer)
- Parameters:
targetBuffer –
TargetBuffer
- Return type:
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.
- initializeGL()#
This virtual function is called once before the first call to
paintGL()
orresizeGL()
. 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 topaintGL()
instead.See also
- isValid()#
- Return type:
bool
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.
- 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()
.See also
- makeCurrent(targetBuffer)
- Parameters:
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()
.See also
- 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.
The default implementation performs a glClear(). Subclasses are not expected to invoke the base class implementation and should perform clearing on their own.
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 theQOpenGLWidget
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.
- resizeGL(w, h)#
- Parameters:
w – int
h – int
This virtual function is called whenever the widget has been resized. Reimplement it in a subclass. The new size is passed in
w
andh
.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
- resized()#
This signal is emitted right after the framebuffer object has been recreated due to resizing the widget.
- setFormat(format)#
- Parameters:
format –
QSurfaceFormat
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 theQOpenGLWidget
.See also
format()
setDefaultFormat()
- setTextureFormat(texFormat)#
- Parameters:
texFormat – int
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
- setUpdateBehavior(updateBehavior)#
- Parameters:
updateBehavior –
UpdateBehavior
Sets this widget’s update behavior to
updateBehavior
.See also
- textureFormat()#
- Return type:
int
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
None
ifsetTextureFormat()
was not called and the widget has not yet been made visible.See also
- updateBehavior()#
- Return type:
Returns the update behavior of the widget.
See also