Search code examples
c++qtopenglgraphicsqglwidget

QGLWidget paintEvent: where to initialize openGL?


It seems that the paintEvent method of the QGLWidget is called before initializeGL, so where am I supposed to put my openGL initialization code?

I'm putting it into the paintEvent method like this:

void MyGLWidget::paintEvent(...)
{
   makeCurrent();
   ..save modelview and projection matrices..

   // This is initialization code

   GLenum init = glewInit();
    if (GLEW_OK != init)
    {
      /* Problem: glewInit failed, something is seriously wrong. */
      qWarning() << glewGetErrorString(init);
    }

    // Dark blue background
    glClearColor(0.2f, 0.0f, 0.5f, 0.0f);
    // Enable depth test
    glEnable(GL_DEPTH_TEST);


   // End initialization code

   ... drawing code

   QPainter painter(this);
   ...overpainting..

}

I really don't like the idea of having my glew library initialization function called every time a paintEvent is raised... although that's working.

Any suggestion?


Solution

  • You have to initialize OpenGL in initializeGL(), there is no other option.

    But you also have to draw inside paintGL, not inside paintEvent, so that is where your mistake is.