1
votes

I have a QGraphicsScene in which I add a QGraphicsItem. Inside the QGraphicsItem, I render the triangle used in the hello triangle example of OpenGL ES 2.0. The problem is that if I create and compile the shaders anyplace other than the QGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) function, they do not get compiled. I know that you should have a GL rendering context active but doesn't that happen when I set my viewport to a GLWidget?? I tried various things like compiling them in the QGraphicsItem constructor or in the QGraphicsScene and setting the QGraphicsItem as a parent (which I learned they are very stupid things to do), but (obviously) nothing works. What seemed most logical to me was to create a initShaders() function inside the QGraphicsItem class and call it after the item is created in my scene, but that didn't work also.

1

1 Answers

3
votes

Create a derived class of QGraphicsView. Override the setupViewport(QWidget *viewport) to initialize the shaders. This will allow you to ensure the context is current when compiling the shaders. However, it requires that the items be added to the scene before setViewport() is called on the graphics view.

void MyGraphicsView::setupViewport(QWidget *viewport)
{
    QGLWidget *glWidget = qobject_cast<QGLWidget*>(viewport);
    if (glWidget) {
        glWidget->makeCurrent();
        foreach (QGraphicsItem *item, scene()->items())
        {
            MyGraphicsShaderItem *glItem = qgraphicsitem_cast<MyGraphicsShaderItem*>(item);
            if (glItem)
                glItem->initShader();
        }
        glWidget->doneCurrent();
    }
}