我在顶级小部件中有两个QOpenGLWidget
s( view1
, ) 作为子级。view2
Qt 文档说“当多个 QOpenGLWidgets 作为子级添加到同一个顶级小部件时,它们的上下文将相互共享”。所以,view1
并view2
分享 OpenGL 上下文。我试图渲染在view1
's context 中初始化的相同场景,并且应用程序在 view2's 中崩溃paintGL()
。我做错了什么?
这是简化的代码:
#include <QtGui/QtGui>
#include <QtWidgets/QOpenGLWidget>
#include <QtWidgets/QApplication>
#include <QtWidgets/QHBoxLayout>
static const char *vertexShaderSource =
"attribute vec4 posAttr;\n"
"void main() {\n"
" gl_Position = posAttr;\n"
"}\n";
static const char *fragmentShaderSource =
"void main() {\n"
" gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n"
"}\n";
QOpenGLShaderProgram *program = nullptr;
QOpenGLBuffer arrayBuf;
int posAttr = -1;
class View3D : public QOpenGLWidget {
public:
View3D()
{
setMinimumSize(300, 200);
}
private:
auto initializeGL() -> void override
{
if (program)
return;
program = new QOpenGLShaderProgram(this);
program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource);
program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource);
program->link();
posAttr = program->attributeLocation("posAttr");
program->bind();
GLfloat vertices[] = {
0.0f, 0.707f, 0.f,
-0.5f, -0.5f, 0.f,
0.5f, -0.5f, 0.f,
};
arrayBuf.create();
arrayBuf.bind();
arrayBuf.allocate(vertices, sizeof(vertices));
program->enableAttributeArray(posAttr);
program->setAttributeBuffer(posAttr, GL_FLOAT, 0, 3, 0);
program->release();
}
auto paintGL() -> void override
{
auto f = context()->functions();
const auto dpr = devicePixelRatio();
f->glViewport(0, 0, width() * dpr, height() * dpr);
f->glClear(GL_COLOR_BUFFER_BIT);
program->bind();
arrayBuf.bind();
program->enableAttributeArray(posAttr);
f->glDrawArrays(GL_TRIANGLES, 0, 3);
program->disableAttributeArray(posAttr);
arrayBuf.release();
program->release();
}
};
auto main(int argc, char **argv) -> int
{
QApplication app{argc, argv};
QWidget w;
auto hbox = new QHBoxLayout{&w};
hbox->addWidget(new View3D); // view1
hbox->addWidget(new View3D); // view2
w.show();
return app.exec();
}