Use OpenGL context in outer class in Qt

I have a window in Qt that inherits from QGLViewer. If I create any shader program in this class, QGLShaderProgram myShadereverything will be fine.

However, I start moving the rendering calls to classes outside the class with the call draw(), and everything breaks.

The application compiles without errors, but when I executed it, I received an error message The program has unexpectedly finished.

I found that from Qt4 to Qt5, the shader class has changed, being the QOpenGLShaderProgramone used in Qt5. I gave it a try and the same problem arose, however, I got a different error message QOpenGLFunctions created with a non-current context.

Which makes me think that when calling OpenGL functions from a class that is not directly related to the class that actually makes the drawing, the OpenGL context is β€œlost”.

How can I make the context visible in all classes? In general, my code looks like

Myviewer.hpp

class MyViewer : public QGLViewer
{
   MyViewer(const QGLFormat format);
   ~MyViewer();

protected:
   init();
   draw()
   {
      // Clear color buffer and depth buffer
      // Do stuff
      m_cube.render();
   }
private:
   ...
   ...

   Cube m_cube;
};

Cube.cpp

class Cube
{
public:
   Cube()
   {
      m_shaderProgram.addShaderFromSourceFile(QGLShader::Vertex, ":/vertex.glsl");
      m_shaderProgram.addShaderFromSourceFile(QGLShader::Fragment, ":/fragment.glsl");
      m_shaderProgram.link();

      //Initialize VAO and VBOs
   }

   void render(){ // render OpenGL calls }

private:
   QGLShaderProgram m_shaderProgram;
};
+4
source share
1 answer

Open global contexts are global, but you can explicitly use the context between two viewers

QGLViewer   (   QGLContext *    context,
        QWidget *   parent = 0,
        const QGLWidget *   shareWidget = 0,
        Qt::WindowFlags     flags = 0 
    )   

A according to ducumentation

Same as QGLViewer (), but QGLContext can be provided so that viewers share GL contexts, even with QGLContext subclasses (use shareWidget otherwise).

, , . Cube opengl, vieuwer opengl , QGLviewer , .

Qglcontext .

Cube() {}; // empty cube constructor
void InitShaders()
   {
      m_shaderProgram.addShaderFromSourceFile(QGLShader::Vertex, ":/vertex.glsl");
      m_shaderProgram.addShaderFromSourceFile(QGLShader::Fragment, ":/fragment.glsl");
      m_shaderProgram.link();

      //Initialize VAO and VBOs
   }

do

MyViewer(const QGLFormat format){
    cube.initShaders();

}

, .

0

All Articles