无法使用 QGLWidget 获取 OpenGL 3.3 功能 (Linux)

Cannot get OpenGL 3.3 functions with QGLWidget (Linux)

我遇到了一个非常奇怪的问题,所以我写了一个最小的例子来重现它。

首先我从QGLWidget推导出class:

class Demo : public QGLWidget
{
public:
    struct error {};

    explicit Demo( const QGLFormat& format ) : QGLWidget( format )
    {
    }

protected:
    virtual void initializeGL() override
    {
        const GLenum glewState = glewInit();
        if( glewState != GLEW_OK ) throw error();
        unsigned int id;
        glGenSamplers( 1, &id ); //<-- Note this here!
    }
};

这里是 main 函数:

int main( int argc, char** argv )
{
    QApplication app( argc, argv );
    QGLFormat format = QGLFormat::defaultFormat();
    format.setVersion( 3, 3 );
    Demo demo( format );
    demo.show();
    return QApplication::exec();
}

我使用 G++ 4.9 构建此代码。当我使用 GDB 运行 时,这是我得到的:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
(gdb) bt
#0  0x0000000000000000 in ?? ()
#1  0x0000000000402add in Demo::initializeGL() () at test.cpp:16
...

显然函数glGenSamplers指向0。我还添加了另一行

if( glGenSamplers == nullptr ) throw error();

验证一下,没错,就是这里报错了。但为什么?我错过了什么?

解决方案是强制 QGLWidget 兼容配置文件:

format.setProfile( QGLFormat::Compatibility );

虽然我不明白为什么glGenSamplers需要这个。据我了解,此功能实际上应该是自 3.3 以来的核心配置文件的一部分。