You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Qt6中使用旧版OpenGL函数调用?

解决Qt 6.4中旧版OpenGL固定管线函数的访问问题

1. 启用兼容模式的OpenGL上下文

glEnableClientState、glVertexPointer这类旧函数属于OpenGL固定管线特性,仅在**兼容模式(Compatibility Profile)**下可用。先为你的OpenGL部件设置兼容模式上下文:

// 在QOpenGLWidget子类的构造函数中配置格式
MyGLWidget::MyGLWidget(QWidget *parent) : QOpenGLWidget(parent)
{
    QSurfaceFormat format;
    format.setVersion(1, 4); // 指定使用OpenGL 1.4版本
    format.setProfile(QSurfaceFormat::CompatibilityProfile); // 启用兼容模式
    format.setOption(QSurfaceFormat::DeprecatedFunctions); // 允许使用废弃函数
    setFormat(format);
}

2. 正确继承旧版OpenGL函数类

不要直接子类化QOpenGLFunctions_1_4_CoreBackend或QOpenGLFunctions_1_4_DeprecatedBackend——这些是Qt内部实现类,不对外公开使用。正确做法是继承官方提供的QOpenGLFunctions_1_4_Deprecated类:

#include <QOpenGLWidget>
#include <QOpenGLFunctions_1_4_Deprecated>

class MyGLWidget : public QOpenGLWidget, protected QOpenGLFunctions_1_4_Deprecated
{
    Q_OBJECT
protected:
    void initializeGL() override;
    void paintGL() override;
    void resizeGL(int w, int h) override;
};

3. 初始化OpenGL函数

在initializeGL方法中调用initializeOpenGLFunctions(),加载所有旧版函数的指针:

void MyGLWidget::initializeGL()
{
    // 初始化旧版兼容函数,失败则终止程序
    if (!initializeOpenGLFunctions()) {
        qFatal("Failed to initialize OpenGL 1.4 deprecated functions");
    }

    // 现在可以正常调用旧函数
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glColor4fv(colorData);
    // ... 其他旧函数调用
}

4. 替代方案:动态获取单个函数指针

如果不想继承旧版函数类,也可以在初始化时单独获取目标函数的指针:

void MyGLWidget::initializeGL()
{
    QOpenGLContext* ctx = context();
    // 获取glVertexPointer的函数指针
    PFNGLVERTEXPOINTERPROC glVertexPointer =
        reinterpret_cast<PFNGLVERTEXPOINTERPROC>(ctx->getProcAddress("glVertexPointer"));
    // 获取glEnableClientState的函数指针
    PFNGLENABLECLIENTSTATEPROC glEnableClientState =
        reinterpret_cast<PFNGLENABLECLIENTSTATEPROC>(ctx->getProcAddress("glEnableClientState"));

    if (!glVertexPointer || !glEnableClientState) {
        qFatal("Failed to get deprecated OpenGL function pointers");
    }

    // 通过指针调用函数
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(3, GL_FLOAT, 0, vertexData);
}

常见问题排查

  • 若找不到QOpenGLFunctions_1_4_Deprecated,确认项目文件中已添加QT += opengl,且包含了头文件<QOpenGLFunctions_1_4>。
  • 子类化Backend类出现构造器报错,是因为这些类的构造器并非公开接口,必须使用官方提供的QOpenGLFunctions_X_Y_Deprecated系列类。

内容的提问来源于stack exchange,提问作者begleysm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:40:13