【问题标题】:How to create QOffscreenSurface with alpha?如何使用 alpha 创建 QOffscreenSurface?
【发布时间】:2026-02-24 18:30:01
【问题描述】:

找到example of offscreen rendering in QT(更新 1 中有一个工作代码)。

但无法使其支持 alpha,请参见下面的代码:

    QSurfaceFormat surfaceFormat;
    surfaceFormat.setColorSpace(QSurfaceFormat::ColorSpace::sRGBColorSpace);
    surfaceFormat.setRenderableType(QSurfaceFormat::RenderableType::OpenGL);
    surfaceFormat.setMajorVersion(4);
    surfaceFormat.setMinorVersion(3);
    surfaceFormat.setAlphaBufferSize(8);

    if (surfaceFormat.hasAlpha())
    {
        qInfo() << "The surface has alpha.";
    }
    else
    {
        qInfo() << "The surface does not have alpha.";
    }

它总是打印“表面有 alpha”。但是我的屏幕外渲染没有 alpha 或者更确切地说我得到了一个奇怪的效果,透明像素变成白色,而背景是黑色:

将其与不透明的原始图像进行比较:

区别在于片段着色器中的vec4(fragColor, 0.5)vec4(fragColor, 1.0)

program.addShaderFromSourceCode(QOpenGLShader::Fragment,
                               "#version 330\r\n"
                               "in vec3 fragColor;\n"
                               "out vec4 color;\n"
                               "void main() {\n"
                               "    color = vec4(fragColor, 1.0);\n"
                               "}\n"
                               );

我可以设置其他选项吗?

我的环境:Windows 10、MSVC 2019、QT 6.2。

EDIT1:

在渲染三角形之前做了一些进一步的实验并添加了以下内容:

        glDisable(GL_DEPTH_TEST);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glBlendEquation(GL_FUNC_ADD);
        glClearColor(0, 0, 0, 0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

得到白色背景:

glClearColor(0, 0, 0, 0.5) 我变灰了:

【问题讨论】:

标签: qt qt6 qtopengl


【解决方案1】:

您的图像查看器在白色背景上显示您的图像,以便您看到白色或灰色。使用glClearColor(0, 0, 0, 1),您将在黑色背景上看到一个透明三角形:

    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glBlendEquation(GL_FUNC_ADD);
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

但生成的三角形将部分透明,因此白色图像查看器背景将在三角形下方部分可见。

【讨论】: