The Qt documentation says:
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.
This is my case with Qt 6.4.1 (MSVC2019, Windows 10). When I dynamically add a new QOpenGLWidget
to my window, the window closes and opens again. That is not good.
I found a workaround. Just add to the layout and then remove an empty QOpenGLWidget
before the window is shown:
void MainWindow::showEvent( QShowEvent* event )
{
Q_UNUSED( event )
QOpenGLWidget w;
layout()->addWidget( &w );
layout()->removeWidget( &w );
}
But it seems like a dirty solution.. Does anyone know a more elegant way to force Qt to use the OpenGL window type by default?
UPD
The MainWindow
class in the code above is derived from QWidget
. I tried to call windowHandle()->setSurfaceType(..)
in the MainWindow::showEvent
. It leads to the app crash when I then create the QOpenGLWidget
. Since MainWindow
is QWidget
, I can't use windowHandle()
in the ctor because a window object is not created yet.