qtopenglqgraphicsviewqglwidget

calling Qt's QGraphicsView::setViewport with a custom QGLWidget


I've derived from QGLWidget before, like so:

class MyGLWidget : public QGLWidget
{
public:
   // stuff...

   virtual void initializeGL() { /* my custom OpenGL initialization routine */ }

   // more stuff...
};

However, I find that if I try to initialize a QGraphicsView with my custom QGLWidget as the viewport, initializeGL doesn't get called (setting a breakpoint within the Qt library, neither does QGLWidget::initializeGL() when created plain).

// initializeGL, resizeGL, paintGL not called
ui.graphicsView->setViewport(new MyGLWidget(QGLFormat(QGL::DoubleBuffer)));

// initializeGL, resizeGL, paintGL *still* not called
ui.graphicsView->setViewport(new QGLWidget(QGLFormat(QGL::DoubleBuffer)));

Where is the correct location to place the code that currently resides in MyGLWidget::initializeGL()?


Solution

  • I'm going to go ahead and answer my own question. This isn't optimal, but this is how I've gotten around the problem.

    Instead of

    ui.graphicsView->setViewport(new MyGLWidget(QGLFormat(QGL::DoubleBuffer)));
    

    I've got this instead:

    ui.graphicsView->setViewport(new QGLWidget(new CustomContext(QGLFormat(QGL::SampleBuffers))));
    

    CustomContext is a class that derives from QGLContext. I've overridden the create member, like so:

    virtual bool create(const QGLContext *shareContext = 0)
    {
        if(QGLContext::create(shareContext))
        {
            makeCurrent();
    
            /* do my initialization here */
    
            doneCurrent();
    
            return true;
        }
    
        return false;
    }
    

    I don't think this is the optimal way to do this, but it's better than the alternative of not having a specific initialization step at all. I'd still be happy to have someone leave a better answer!