QOpenGLWidget 立体渲染示例
本示例演示了如何创建一个支持立体渲染的、基于QOpenGLWidget 的简易应用程序。
注意: 立体渲染功能 需要满足一定的硬件要求,例如支持立体显示的显卡、3D眼镜以及特定的显示器。
注意:本示例将 两张图像渲染到两个独立的缓冲区中。当您通过 3D 眼镜观看这些图像时,会产生 3D 全息效果。

上图即为将渲染到左侧缓冲区的内容。

上图是渲染到右侧缓冲区的内容。
设置正确的表面标志
要启用立体渲染,需要在全局范围内设置QSurfaceFormat::StereoBuffers 标志。仅在小部件上设置是不够的,因为该标志在内部的处理方式有其特殊性。最稳妥的做法是在启动应用程序之前,通过QSurfaceFormat::SetDefaultFormat进行设置。
QSurfaceFormat format;
format.setDepthBufferSize(24);
format.setStencilBufferSize(8);
// Enable stereoscopic rendering support
format.setStereo(true);
QSurfaceFormat::setDefaultFormat(format);两次渲染
设置QSurfaceFormat::StereoBuffers 后,paintGL() 将被调用两次,每个缓冲区各一次。在 paintGL() 中,您可以调用 currentTargetBuffer() 来查询当前哪个 TargetBuffer 处于活动状态。
在下面的代码片段中,我们对矩阵进行了微小的平移,以避免顶点重叠渲染。这是一个简单的示例,仅用于验证:如果系统提供了必要的支持,运行时您应该会看到两个对象,一个在左侧,一个在右侧。
// Slightly translate the model, so that there's a visible difference in each buffer.
QMatrix4x4 modelview;
if (currentTargetBuffer() == QOpenGLWidget::LeftBuffer)
modelview.translate(-0.4f, 0.0f, 0.0f);
else if (currentTargetBuffer() == QOpenGLWidget::RightBuffer)
modelview.translate(0.4f, 0.0f, 0.0f);© 2026 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.